emGee Software Solutions Custom Database Applications

Share this

Web Design

Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes

Tuts+ Code - Web Development - Fri, 11/24/2017 - 04:00

So far in this series, you have learned how to animate the CSS properties of different elements, how to create different SVG-related animations, and how to animate the text content of different elements on a webpage. There is one more way in which you can animate the elements on a webpage using KUTE.js, and that is by changing the values of different attributes. This requires you to include the attributes plugin in your project.

In this tutorial, you will learn how to use the attributes plugin to animate the value of different kinds of attributes in KUTE.js. We will also discuss different easing functions that you can use to control the pace of different animations.

Easing Functions

Objects in real life very rarely move linearly. They are either accelerating or decelerating. Even the acceleration and deceleration occur at different magnitudes. Up to this point, all our animations have progressed linearly. This doesn't feel natural at all. In this section, you will learn about all the easing functions that KUTE.js provides for controlling the pace of different animations.

The core easing functions in the library are included in the core engine out of the box. Let's say you want to apply the QuadraticInOut easing to an animation. This can be achieved in two ways:

easing: KUTE.Easing.easingQuadraticInOut // OR easing: 'easingQuadraticInOut'

Each of the easing functions has a unique curve that determines how the elements will accelerate during the animation. A sinusoidal curve implies linear acceleration. Keep in mind that this is different from the linear easing function. The linear function implies a linear speed of animation, while a sinusoidal curve implies a linear speed of acceleration for the animation. In other words, the speed of the animation will increase or decrease linearly. Similarly, quadratic implies acceleration with a power of two, cubic implies a power of three, quartic implies a power of four, and quintic implies a power of five. There are also circular and exponential easing functions.

You can append In, Out, or InOut to any of the easing functions. The value In implies that the animation will start very slowly and keep accelerating until the end. The value Out implies that the animation will start at the maximum speed and then decelerate slowly until it comes to a halt at the end. The value InOut means that the animation will speed up at the beginning and slow down at the end.

You can also use bounce and elastic easing functions in your animations and append In, Out, or InOut to any of them. In the following demo, I have applied all these easing functions on different circles so that you can see how they affect the pace of the animation.

It is possible that none of the core easing functions provide the animation pace that you are looking for. In such cases, you can include the Cubic Bezier functions in your project from the experiments branch and start using those easing functions. 

Similarly, KUTE.js also provides some physics-based easing functions imported from the Dynamics.js library. You can read more about all these easing functions and how to properly use them on the easing function page of the library.

Animating Attributes

Attributes in SVG can accept numbers as well as strings as their value. The strings can be color values or numbers suffixed with a unit like px, em, or %. The names of the attributes themselves can also consist of two words joined by a hyphen. Keeping these differences in mind, KUTE.js provides us different methods that can be used to specify the values of different attributes.

var tween = KUTE.to('selector', {attr: {'r': 100}}); var tween = KUTE.to('selector', {attr: {'r': '10%'}}); var tween = KUTE.to('selector', {attr: {'stroke-width': 10}}); var tween = KUTE.to('selector', {attr: {strokeWidth: 10}});

As you can see, suffixed values need to be enclosed within quotes. Similarly, attributes which contain a hyphen in their name need to be enclosed inside quotes or specified in camelCase form.

Unitless Attributes

A lot of attributes accept unitless values. For example, the stroke-width of a path could be unitless. Similarly, you don't have to specify a unit for the r, cx, and cy attributes of a circle element. You can animate all these attributes from one value to another using the attributes plugin. 

Now that you know how to use different easing functions, you will be able to animate different attributes at different paces. Here is an example:

var radiusAnimation = KUTE.allTo( "circle", { attr: { r: 75 } }, { repeat: 1, yoyo: true, offset: 1000, easing: 'easingCubicIn' } ); var centerxAnimationA = KUTE.to( "#circle-a", { attr: { cx: 500 } }, { repeat: 1, yoyo: true, easing: 'easingCubicInOut', } ); var centerxAnimationB = KUTE.to( "#circle-b", { attr: { cx: 100 } }, { repeat: 1, yoyo: true, easing: 'easingCubicInOut' } ); var centeryAnimation = KUTE.allTo( "circle", { attr: { cy: 300 } }, { repeat: 1, yoyo: true, offset: 1000, easing: 'easingCubicOut' } );

The first tween animates the radius of both circles at once using the allTo() method we discussed in the first tutorial. If set to true, the yoyo attribute plays the animation in the reverse direction. 

The cx attribute of both the circles is animated individually. However, they are both triggered by the same button click. Finally, the cy attribute of both the circles is animated at once with an offset of 1000 milliseconds.

Color Attributes

Starting from version 1.5.7, the attribute plugin in KUTE.js also allows you to animate the fill, stroke, and stopColor attributes. You can use valid color names or hex values for the colors. You can also provide the color values in RGB or HSL format. 

One important thing that you have to keep in mind is that the animations will only seem to work if you are not setting the value of these properties in CSS. In the following demo, the fill color wouldn't have animated at all if I had added the following CSS in our demo.

rect { fill: brown; }

The demo I created is very basic, but you can make it more interesting by applying transforms and using more colors.

Suffixed Attributes

A lot of SVG attributes like r and stroke-width can work with and without suffixes. For example, you can set the value of r to be a number like 10 or in terms of em units like 10em. There are some attributes like offset attribute for color stops that always require you to add a suffix. While specifying a value for suffixed attributes in KUTE.js, always make sure that you enclose the value within quotes.

In the following example, I have animated the offset value of the first stop in a gradient and the color of the second stop. Since offset requires a suffix, I have enclosed the value inside quotes.

var offsetAnimation = KUTE.allTo( ".stop1", { attr: { offset: '90%'} }, { repeat: 1, offset: 1000, yoyo: true, easing: 'easingCubicIn' } ); var colorAnimation = KUTE.allTo( ".stop2", { attr: { stopColor: 'black'} }, { repeat: 1, offset: 1000, yoyo: true, easing: 'easingCubicIn' } ); var scaleAnimation = KUTE.allTo( "circle", { svgTransform: { scale: 2} }, { repeat: 1, offset: 1000, yoyo: true, easing: 'easingCubicIn' } );

There are three different gradients in the demo, and each of these gradients has two color stops with the class names stop1 and stop2. I have also applied a scale transform using the svgTransform attribute, which we discussed in the third tutorial of the series.

Final Thoughts

In this tutorial, you learned about different easing functions available in KUTE.js and how you can use them to control the pace of your own animations. You also learned how to animate different kinds of attributes.

I have tried to cover all the important aspects of KUTE.js in this series. This should be enough to help you use KUTE.js confidently in your own projects. You can also read the documentation in order to learn more about the library. 

I would also recommend that you go through the source code and see how the library actually works. If you have any questions or tips related to this tutorial, feel free to share them in the comments.

Categories: Web Design

Building Accessible Menu Systems

Smashing Magazine - Thu, 11/23/2017 - 08:25
Editor’s Note: This article originally appeared on Inclusive Components. If you’d like to know more about similar inclusive component articles, follow @inclusicomps on Twitter or subscribe to the RSS feed. By supporting inclusive-components.design on Patreon, you can help to make it the most comprehensive database of robust interface components available. Classification is hard. Take crabs, for example. Hermit crabs, porcelain crabs, and horseshoe crabs are not — taxonomically speaking — true crabs.
Categories: Web Design

Performant Animations Using KUTE.js: Part 4, Animating Text

Tuts+ Code - Web Development - Thu, 11/23/2017 - 04:00

In the second tutorial of this series, you learned how to animate different CSS properties of the elements on a webpage using KUTE.js. You learned how to animate all the transform properties as well as properties like border-radius and border-color. You can also use the CSS plugin to animate CSS properties like font-size, line-height, letter-spacing, and word-spacing.

KUTE.js also has a Text plugin which allows you to animate the text inside different elements, either by increasing or decreasing a number like in a countdown or by writing a string character by character.

In this tutorial, you will learn how to animate the text inside different elements on a webpage using the CSS and Text plugins in KUTE.js.

Animating CSS Text Properties

As I mentioned earlier, you can use the KUTE.js CSS plugin to animate four different text-related CSS properties. These properties are font-size, line-height, letter-spacing, and word-spacing. We will also use some properties from the core engine discussed in the first tutorial to animate individual letters. Let's see how we can use all these concepts together to create the vibrating HELLO text in the following demo.

Here is the code that was used to create the above animation:

var theLetters = document.querySelectorAll("span"); var h = document.querySelector(".h"); var e = document.querySelector(".e"); var la = document.querySelector(".la"); var lb = document.querySelector(".lb"); var o = document.querySelector(".o"); var startButton = document.querySelector(".start"); var animateColor = KUTE.allFromTo( theLetters, { color: 'white' }, { color: 'red' }, { offset: 200, duration: 50} ); var animateFontSize = KUTE.allFromTo( theLetters, { fontSize: '2em' }, { fontSize: '4em' }, { offset: 100, duration: 200, repeat: 10, yoyo: true} ); var animateSkewing = KUTE.allTo( theLetters, { skewX: -15}, { offset: 200, duration: 200 } ); var animateH = KUTE.to( h, { color: '#009688' } ); var animateE = KUTE.to( e, { translateY: -40, color: '#E91E63' } ); var animateLA = KUTE.to( la, { color: '#8BC34A' } ); var animateLB = KUTE.to( lb, { translateY: 20, color: '#FFC107' } ); var animateO = KUTE.to( o, { color: '#FF5722' } ); var lettersSqueezed = KUTE.allTo( theLetters, { letterSpacing: '-15px' }, { offset: 0, duration: 200 } ); animateColor.chain(animateFontSize); animateFontSize.chain(animateSkewing); animateSkewing.chain(animateH, animateE, animateLA, animateLB, animateO); animateE.chain(lettersSqueezed); startButton.addEventListener( "click", function() { animateColor.start(); }, false );

Each letter of the word is wrapped inside a span tag and has its own unique class. The first tween animates the color of all the letters from white to red with an offset of 200ms. This is also the first animation that is played after clicking on Start Animation. The animateFontSize tween has been chained to animateColor. This way, the font-size animation begins as soon as the color animation ends. 

You might have noticed that I have used two attributes called repeat and yoyo to control the behavior of the animation. The yoyo attribute is used to reverse the animation that is currently being played repeatedly. This can avoid sudden jumps in the values of different properties during the animation and make it appear smooth.

The font-size animation has been chained with animateSkewing, which skews all the letters by -15 degrees. The skewX and skewY properties are available within the core engine itself.

All the tweens for animating the color of different letters have been chained to animateSkewing at once. This way, you can make sure that all the chained color animations start playing as soon as the skew animation ends. Finally, the lettersSqueezed tween reduces the spacing between different letters by 15 px.

You can create more interesting effects by using different combinations of properties.

Animating Numbers

You can also animate numbers in KUTE.js. However, you will have to include an additional text plugin to create the animation. 

The process of animating numbers is actually very simple. You just need to specify the selector where the animating numbers should be shown as well as the final number at which the animation should end. 

Here is a basic example that shows the total number of airports in the USA in 2016 using animation.

var usa = document.querySelector(".usa"); var startButton = document.querySelector(".start"); var animateUSA = KUTE.to( usa, { number: 19536 } ); startButton.addEventListener( "click", function() { animateUSA.start(); }, false );

You can also apply the usual tween options like duration, repeat, and delay to customize the behavior of the animation. The code we just wrote will result in the following animation:

Writing Text Character by Character

This is a very popular effect that you can find on quite a few websites. The KUTE.js text plugin allows you to specify the new sentence that should replace the original sentence one character at a time. 

Before replacing the initial characters with their final value, random characters are animated like the numbers example you just saw. The embedded CodePen demo should make it clearer:

Here is the code that you need to write in order to create the above animation:

var animateHeading = KUTE.to( heading, { text: '70% Surface of Earth is Covered with Water.' }, { duration: 5000} ); startButton.addEventListener( "click", function() { animateHeading.start(); }, false );

The character animation for the whole sentence is finished within 5 seconds. As you might have noticed, the initial and final sentences don't need to have the same number of characters. This gives us a lot of liberty when setting the value of the text parameter.

You can also include HTML tags inside the value of the text parameter and then use CSS to change the appearance of the text that you just animated.

var animateHeading = KUTE.to( heading, { text: '70% SURFACE OF <span class="earth">EARTH</span> IS COVERED WITH <span class="water">WATER</span>.' }, { duration: 10000, textChars: 'upper' } );

There will be a delay in the appearance of Earth after of has already appeared. This happens because the plugin also writes <span class="earth"> using the same character animation, but none of those characters are actually visible to the user. The delay may or may not be desirable based on your preferences.

The intermediate characters that are shown during the animation are lowercase alphabetical values by default. This can be an issue when the characters that you want to animate are all uppercase letters or numbers. Which intermediate characters are used for the animation is determined by the value of the textChars parameter. It accepts six different values:

  • alpha: In this case, the intermediate characters will be lowercase letters.
  • upper: In this case, the intermediate characters will be uppercase letters.
  • numeric: In this case, numerical characters are used for the animation. This is different from animating a number as the values won't increase sequentially.
  • symbols: In this case, the plugin will use characters like #, %, and $ for the animations.
  • all: You can use this value if you want the intermediate characters to be a mix of alphabetic, numeric, and symbols.
  • If nothing else works for you, KUTE.js gives you the option of specifying your own custom list of characters that should be used during the animation.

The following example shows how you can animate text inside a heading using uppercase intermediate characters.

Final Thoughts

In this tutorial, you learned how to use the CSS and Text plugins in KUTE.js to animate the text inside an element. When you want to animate the appearance of the text, you need to use the CSS plugin. This will allow you to use properties like font-size, letter-spacing, etc. When you want to change the actual characters inside any element, you need to use the text plugin.

If you’re looking for additional JavaScript resources to study or to use in your work, check out what we have available on Envato Market.

I hope you learned something new in this tutorial. If you have any questions, please let me know in the comments.

Categories: Web Design

Save $$$ on Web Hosting For Black Friday and Cyber Monday 2017

Who Is Hosting This Feed - Wed, 11/22/2017 - 17:37

Update for Monday, Nov 27 — Cyber Monday deals are now live. The holiday shopping season is just around the corner and that means that Black Friday is almost here to kick it all off. Traditionally, Black Friday marks the biggest sales of the year both in the traditional and online retail world. It’s also […]

The post Save $$$ on Web Hosting For Black Friday and Cyber Monday 2017 appeared first on Who Is Hosting This: The Blog.

Categories: Web Design

The New Smashing Mystery Riddle, An Emoji Edition

Smashing Magazine - Wed, 11/22/2017 - 09:38
Oh yes, the infamous mystery riddles are back! At this point, you might be used to endless, mischievous, tricky, mean, time-consuming and intricate Mystery Riddles, and the new one is no different. To celebrate the relaunch of this little website, we've prepared something special yet again — a Smashing Emoji Mystery Riddle. And this time, instead of scouting an answer in a physical place or on Twitter, it's well hidden somewhere on this website.
Categories: Web Design

Performant Animations Using KUTE.js: Part 3, Animating SVG

Tuts+ Code - Web Development - Wed, 11/22/2017 - 04:00

The previous tutorial of the series showed you how to animate different CSS properties of any element using KUTE.js. However, the core engine does not allow you to animate properties that are specific to SVG elements. Similarly, you can't animate the SVG morphing of different path shapes or the drawing of different SVG elements using strokes. You will have to use the KUTE.js SVG plugin to achieve any of these tasks.

Before we begin, keep in mind that you will have to include both the KUTE.js core engine and the SVG plugin for the examples in this tutorial to work.

Morphing SVG Shapes

Morphing one SVG shape into another is a very common feature that you will come across. The KUTE.js SVG plugin gives us everything that we need to create our own morphing animations with ease. 

There are three ways to morph SVG shapes using this library:

  1. You can use the fromTo() method to specify both the initial and the final SVG path for your element. 
  2. You can also use the to() method and avoid specifying the initial path. In this case, the start value for the morphing will be determined based on the value of the d attribute of the selected element that you want to morph. 
  3. One more option that you have is to pass the final path as a string directly to the tween. This way, you can avoid having two different paths in your SVG.
KUTE.fromTo('#shape-a', {path: '#shape-a' }, { path: '#shape-b' }); KUTE.to('#shape-a', { path: '#shape-b' }); KUTE.fromTo('#shape-a', {path: '#shape-a' }, { path: 'The path of #shape-b as a valid string.' }); KUTE.to('#shape-a', { path: 'The path of #shape-b as a valid string.' });

During initialization, the library samples some points based on the paths that we provided. These points are then stored in two different arrays. Finally, these arrays are used for the interpolation. There are a number of options that you can configure to control the morphing behavior for different paths.

  • morphPrecision: As you might have guessed, this option allows you to specify the precision or accuracy of the morphing. It is specified as a number, and a lower value means higher precision. Keep in mind that higher precision will result in more accuracy, but it will also be detrimental to the performance. This option does not apply when you are dealing with polygonal shapes or paths where the d attribute consists only of h, l, and v. In such cases, the original polygon paths are used instead of sampling new ones.
  • reverseFirstPath: You can set the value of this option to true in order to reverse the drawing path for your first shape. Its default value is false.
  • reverseSecondPath: You can set the value of this option to true in order to reverse the drawing path for your second shape. Its default value is also false.
  • morphIndex: Sometimes, the points on a path might have to cover a lot of distance during morphing. You can control this behavior using the morphIndex parameter. When specified, this parameter allows you to rotate the final path in such a way that all the points travel the least distance possible.

Let's use what we have learned so far to morph a battery icon into a bookmark icon. You should note that I have used lowercase l in order to specify the path in relative terms. This is the required markup:

<path id="battery-a" d="M50,10 l150,0 l0,25 l20,0 l0,50 l-20,0 l0,25 l-150,0 l0,-100z"/> <path id="bookmark-a" d="M70,10 l0,125 l40,-40 l40,40 l0,-125 l0,0 l0,0 l0,0 l0,0z"/>

The following JavaScript creates the tween object and starts the animation on button click:

var morphA = KUTE.to( '#battery-a', { path: '#bookmark-a' }, { duration: 5000 } ); startButton.addEventListener( "click", function() { morphA.start(); }, false );

Here is a demo that shows the above code in action. I have also added an extra element where the morph animation sets reverseFirstPath to true. This will help you understand the overall impact of different configuration options on the morphing. The animation duration has been set to 5 seconds so that you can closely observe both the animations and spot the differences.

In the previous example, the main path did not have any subpaths. This made the morphing very straightforward. However, this might not always be the case. 

Let's add an extra subpath to our bookmark as well as the battery icon. If you morph the icons now, you will see that only the first subpath animates. The second subpath just disappears at the beginning of the animation and reappears at the end. The only way to animate all the subpaths in such cases is by changing the subpaths into individual paths. Here is an example:

<!-- Before --> <path id="battery-a" d="M50,10 l150,0 l0,25 l20,0 l0,50 l-20,0 l0,25 l-150,0 l0,-100z M70,30 l60,65 l-10,-65 l60,65z"/> <path id="bookmark-a" d="M70,10 l0,125 l40,-40 l40,40 l0,-125 l0,0 l0,0 l0,0 l0,0z M80,80 l30,-45 l30,45 l0,0z"/> <!-- After --> <path id="battery-b1" d="M250,10 l150,0 l0,25 l20,0 l0,50 l-20,0 l0,25 l-150,0 l0,-100z"/> <path id="battery-b2" d="M270,30 l60,65 l-10,-65 l60,65z"/> <path id="bookmark-b1" d="M270,10 l0,125 l40,-40 l40,40 l0,-125 l0,0 l0,0 l0,0 l0,0z"/> <path id="bookmark-b2" d="M280,80 l30,-45 l30,45 l0,0z"/>

Animating SVG Strokes

Another popular SVG-related animation effect includes starting from nothing and then drawing a predefined shape using SVG strokes. This can be used to animate the drawing of logos or other objects. In this section, you will learn how to use KUTE.js to create a stroking animation for the Font Awesome bicycle icon

There are three ways to animate SVG strokes in KUTE.js. You can animate from 0% to 100% by setting the fromTo values as 0% 0% and 0% 100%. You can also draw a part of the SVG shape by setting the values to something like 0% 5% and 95% 100%. Finally, you can set the ending value to 0% 0% in order to create an erasing effect instead of a drawing effect.

Here is the JavaScript code that I have used to animate our bicycle:

var wholeAnimation = KUTE.fromTo( "#icon", { draw: "0% 0%" }, { draw: "0% 100%" }, { duration: 10000} ); var partialAnimation = KUTE.fromTo( "#icon", { draw: "0% 5%" }, { draw: "95% 100%" }, { duration: 10000} ); var eraseAnimation = KUTE.fromTo( "#icon", { draw: "0% 100%" }, { draw: "0% 0%" }, { duration: 5000} );

As you can see in the example below, you don't need to worry about multiple subpaths inside a path. KUTE.js animates all of these subpaths individually without any issues. The animation duration is used to determine the time for the animation of the longest path. The stroke duration for the rest of the subpaths is then determined based on their length.

Animating SVG Transforms

We have already learned how to animate CSS transform values in the second tutorial of the series. The KUTE.js SVG plugin also allows you to use the svgTransform attribute in order to rotate, translate, scale, or skew different SVG elements on a webpage.

The rotate attribute accepts a single value that determines the angle of rotation. By default, the rotation happens around the center point of the element, but you can specify a new center of rotation using the transformOrigin attribute.

The translate attribute accepts the values in the format translate: [x, y] or translate: x. When provided with a single value, the value of y is assumed to be zero.

When skewing elements, you will have to use skewX and skewY. There is no support for skew[x, y] in SVG. Similarly, the scale attribute also accepts only one value. The same value is used to scale the elements in both x and y directions.

Here is a code snippet that applies all these transformations on a rectangle and a circle.

var rotation = KUTE.allTo( "rect, circle", { svgTransform: { rotate: 360 } }, { repeat: 1, yoyo: true } ); var scaling = KUTE.allTo( "rect, circle", { svgTransform: { scale: 1.5 } }, { repeat: 1, yoyo: true } ); var translation = KUTE.allTo( "rect, circle", { svgTransform: { translate: [100, -50] } }, { repeat: 1, yoyo: true } ); var skewing = KUTE.allTo( "rect, circle", { svgTransform: { skewX: 25 } }, { repeat: 1, yoyo: true } );

I have set the yoyo parameter to true so that after playing the animation in reverse, the transform properties are set to their initial value. This way, we can replay the animations again and again by clicking on the buttons.

If you press the Rotate button in the demo, you will notice that it does not seem to have any effect on the circle. To observe the rotation of circle, you will have to apply a skew transform on it in order to change its shape and then click on rotate immediately.

Final Thoughts

We began this tutorial by covering the basics of SVG morphing and stroke animations. You learned how to properly morph complex paths that have subpaths and how we can create an erasing stroke effect instead of a drawing one by choosing the right values for the draw attribute. After that, we discussed how we can use the svgTransform attribute in order to animate different transforms.

In various tutorials, we've seen just how powerful JavaScript has become. It’s not without its learning curves, and there are plenty of frameworks and libraries to keep you busy, as well. If you’re looking for additional resources to study or to use in your work, check out what we have available on Envato Market.

The tutorial was meant to introduce you to all the features of the KUTE.js SVG plugin and help you get started quickly. You can learn more about the SVG plugin by reading the documentation.

Categories: Web Design

From Cats With Love: Welcome The New Smashing Membership

Smashing Magazine - Wed, 11/22/2017 - 02:36
We can’t believe it’s actually happening. After 18 months of hard work on the big bang relaunch of this little website, today is the day when everything changes. New design and new technical stack. New personality and new ambitious goals. But most importantly, a new focus on our wonderful web community, with the brand new Smashing Membership. Rewarding Great People Doing Great Work In times when we fight all the craziness and narrow-mindedness around us, we need to remind ourselves how wonderful a vast majority of the web community actually is.
Categories: Web Design

New Course: Code a Quiz App With Vue.js

Tuts+ Code - Web Development - Tue, 11/21/2017 - 04:18

Single-page web apps are more and more in demand, but they can be hard to build with vanilla JavaScript. Thankfully, there are some powerful frameworks that can make the task easier, such as Vue.js. Learn how to use it in our new course, Code a Quiz App With Vue.js.

What You’ll Learn

In this course, Derek Jensen will show you how easy it is to code an app with the Vue.js framework. 

You'll learn how to create a simple front-end web app using the Vue command-line interface (CLI), create self-contained components, dynamically update the user interface, and even create a simple yet elegant user experience with Semantic UI. 

Follow along and you'll see how, with just a few simple skills, you too can begin building web apps with Vue.

Watch the Introduction Take the Course

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to this course, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 400,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Categories: Web Design

Performant Animations Using KUTE.js: Part 2, Animating CSS Properties

Tuts+ Code - Web Development - Tue, 11/21/2017 - 04:00

The first tutorial of the series focused on providing a beginner-friendly introduction to the KUTE.js library. In that tutorial, we only animated the opacity and rotateZ property for our elements. In this tutorial, you will learn how to animate the rest of the CSS properties using KUTE.js. 

Some of these properties will require you to load the CSS plugin, while others can be animated using the core engine itself. Both these scenarios will be discussed separately in the tutorial.

Box Model Properties

The core KUTE.js engine can animate only the most common box model properties: width, height, top, and left. You will have to use the CSS plugin to animate almost all other box model properties. Here is an example that animates the top position, width and height of our boxes from the previous tutorial:

var animateTop = KUTE.allFromTo( theBoxes, { top: 0 }, { top: 100 }, { offset: 100 } ); var animateA = KUTE.fromTo( boxA, { height: 100 }, { height: 175 } ); var animateB = KUTE.fromTo( boxB, { width: 100 }, { width: 200 } );

You might have noticed that I used allFromTo() to animate the top property of all the boxes. However, I used fromTo() to animate individual boxes. You should remember that the boxes stay in their final state once the animation completes.

With the help of the CSS plugin, you will be able to animate margin, padding, and borderWidth as well. Once you have included the plugin in your project, the rest of the process is exactly the same.

Animating Transform Properties

You can animate almost all the transform properties mentioned in the spec with the help of the core engine itself. There is no need to load the CSS plugin in this case.

You can animate the element translation in 2D space using translate. Similarly, you can use translateX, translateY, and translateZ in order to animate the elements along the respective axes. For the translateZ property to have any effect, you will also have to set a value for the parentPerspective property. Here is an example:

var animateAll = KUTE.allFromTo( theBoxes, { translateY: 0 }, { translateY: 100 }, { offset: 1000 } ); var animateA = KUTE.fromTo( boxA, { translateZ: 0 }, { translateZ: 50 }, { parentPerspective: 100, parentPerspectiveOrigin: "0% 0%" } ); var animateB = KUTE.fromTo( boxB, { translateX: 0 }, { translateX: -200 } ); startButton.addEventListener( "click", function() { animateAll.start(); animateA.start(); animateB.start(); }, false );

If you click the Start Animation button and observe the animation closely, you will see that the red box translates -200 in the X direction first. After that, it moves to its original position and starts translating in the Y direction. The reason for the box to animate translateX first is that we have added a delay for the translateY animation using the offset property.

Just like translation, you can also perform rotations along a specific axis using the rotate, rotateX, rotateY, and rotateZ properties. Since rotateX and rotateY are 3D rotations, you will have to use the perspective property for the rotation animation to work as expected. The following example shows how using the perspective property affects the overall animation for these two properties.

var animateAll = KUTE.allFromTo( theBoxes, { rotate: 0 }, { rotate: 360 }, { offset: 1000 } ); var animateA = KUTE.fromTo( boxA, { rotateY: 0 }, { rotateY: 180 }, { perspective: 100 } ); var animateB = KUTE.fromTo( boxB, { rotateY: 0 }, { rotateY: -180 } ); startButton.addEventListener( "click", function() { animateAll.start(); animateA.start(); animateB.start(); }, false );

In the above example, box A and box B start their rotation along the Y axis at the same time, but the resulting animation is very different because of the perspective property. You might have noticed that the orange box is not performing the rotation around its center that was applied to it using animateAll. This is because all animations have a duration of 500 milliseconds by default, and we are applying both animateAll and animateA on the orange box at the same time. 

Since animateA is applied after animateAll, its animation takes precedence over animateAll. You will see that the common rotation using animateAll is still being applied on the orange box once you increase the animation duration. In other words, you cannot animate different transform properties using multiple tween objects at the same time. All the transform properties that you want to animate should be specified inside a single tween object. The following example should make it clear:

// This will not work as expected var translateAll = KUTE.allFromTo( theBoxes, { translateY: 0 }, { translateY: 100 }, { offset: 1000 } ); var rotateAll = KUTE.allFromTo( theBoxes, { rotate: 0 }, { rotate: 360 }, { offset: 1000 } ); startButton.addEventListener( "click", function() { translateAll.start(); rotateAll.start(); }, false ); // This will work as expected var rtAll = KUTE.allFromTo( theBoxes, { translateY: 0, rotate: 0 }, { translateY: 100, rotate: 360 }, { offset: 1000 } ); startButton.addEventListener( "click", function() { rtAll.start(); }, false );

Using the CSS Plugin

As I mentioned earlier, not all CSS properties can be animated using only the core KUTE.js engine. You need to use an extra CSS plugin to animate properties like padding, margin, background position of images, and other border-related properties. So, before you try any of the examples in this section, you should include the plugin in your project.

<script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute-css.min.js"></script>

Once you have included the plugin, you will be able to animate the border-radius property using borderRadius. You can also animate all the corner border-radius values individually using borderTopLeftRadius, borderTopRightRadius, borderBottomLeftRadius, and borderBottomRightRadius. Here is an example that shows the animation in action.

If you click the Start Animation button, you will notice that the top left border-radius for the red and yellow box is animated after a delay. This is because of the offset property. The rest of the radii are animated as soon as we click on the button. The above example was created using the following code:

var animateAll = KUTE.allFromTo( theBoxes, { borderTopLeftRadius:'0%' }, { borderTopLeftRadius:'100%' }, { offset: 1000 } ); var animateA = KUTE.fromTo( boxA, { borderTopRightRadius:'0%' }, { borderTopRightRadius:'100%' } ); var animateB = KUTE.fromTo( boxB, { borderBottomLeftRadius:'0%' }, { borderBottomLeftRadius:'100%' } ); var animateC = KUTE.fromTo( boxC, { borderBottomRightRadius:'0%' }, { borderBottomRightRadius:'100%' } ); startButton.addEventListener( "click", function() { animateAll.start(); animateA.start(); animateB.start(); animateC.start(); }, false );

We have not chained the tween objects together, so all the animations start at once this time. You can also animate the color of different borders in a similar manner using borderColor, borderTopColor, borderLeftColor, borderBottomColor, and borderRightColor. 

Final Thoughts

In this tutorial, we learned about different CSS properties that can be animated with and without the use of the KUTE.js CSS plugin. If you have any questions, please let me know in the comments.

The next tutorial will cover different animations that can be created using the KUTE.js SVG plugin.

Categories: Web Design

6 Tips On How To Use Human Face To Improve User Experience

Human face is a very powerful tool in designer’s toolbox. The influence that a face can have on people is surprising. However, all too often, we ignore this tool...

The post 6 Tips On How To Use Human Face To Improve User Experience appeared first on Onextrapixel.

Categories: Web Design

A Comprehensive Guide To Web Design

Smashing Magazine - Mon, 11/20/2017 - 19:22
(This is a sponsored post). Web design is tricky. Designers and developers have to take a lot of things into account when designing a website, from visual appearance (how the website looks) to functional design (how the website works). To simplify the task, we’ve prepared this little guide. In this article, I’ll focus on the main principles, heuristics, and approaches that will help you to create a great user experience for your website.
Categories: Web Design

6 Cutting-Edge React Courses

Tuts+ Code - Web Development - Mon, 11/20/2017 - 07:28

React is a JavaScript library for building user interfaces that has taken the web development world by storm. React is known for its blazing-fast performance and has spawned an ecosystem of thousands of related modules on NPM. 

However, in a community that favours choice and flexibility, it can be hard to know where to start! So here are six courses that will get you fully up to speed with the latest in React development. 

Whether you want to master React animation, learn how to work with React Native or Redux, or get your hands dirty building some practical React applications, these courses have you covered.

1. Modern Web Apps With React and Redux

In this course, Envato Tuts+ instructor Andrew Burgess will get you started building modern web apps with React and Redux. 

Starting from nothing, you'll use these two libraries to build a complete web application. You'll start with the simplest possible architecture and slowly build up the app, feature by feature. By the end, you'll have created a complete flashcards app for learning by spaced repetition.

Along the way, you'll get a chance to sharpen your ES6 (ECMAScript 2015) skills and learn the patterns and modules that work best with React and Redux!

  2. Five Practical Examples to Learn React

Sometimes, the best way to learn is just to dive in and do something practical. In this course by Jeremy McPeak, you're going to learn React by writing components that you could incorporate into your own applications.

Along the way, you'll learn all the basics of coding React components. You'll learn about JSX, events, managing state, and passing props. You'll also learn about some other key concepts like higher-order components, lifecycle methods, and using third-party libraries.

  3. Get Started With React Native

Mobile app users expect the performance and features that can only be supplied by native app development. But going native often means that you have to develop your app for multiple platforms. React Native bridges this gap by letting you write your user interface in modern JavaScript and automatically transforming it into native platform-specific views.

In this course, Envato Tuts+ instructor Markus Mühlberger will teach you how to write mobile apps in React Native. You will learn how to create, lay out and style components, provide user interaction, and integrate third-party components into your app. Along the way, you'll build a cool cross-platform fitness app!

  4. Build a Social App With React Native

When you've got started with React Native in the course above, you'll want to put your knowledge to good use. So try this course on building a social app with React Native.

You're with Markus Mühlberger again for this one, and he'll show you how to build a social app easily with a Firebase back-end. You'll also learn some more advanced topics like sophisticated view routing, camera and photo library access, and how to use the device's address book.

  5. How to Animate Your React App

If you want to add some life and engagement to your React app, animation is a great way to do it.

In this course, you'll learn how to add some sparkle to your web app with simple animations. Follow along with Stuart Memo and you'll build a basic to-do app, and then enhance it with UI animation. 

To start, you'll learn how to use React's built-in animation hooks. After you've become proficient with that, you'll move on to react-motion, a very popular and powerful animation library.

  6. Code a Universal React App

Coding a full-stack app has always been hard. Developers have to know completely different sets of languages, tools, libraries, and frameworks for the client and server side. But with React and Node, you can use the same JavaScript code on both the client and server.

In this course, Jeremy McPeak will show you how to write a universal (isomorphic) React app—one that can render on the server or the client. This will let us reuse the same code on the server and client, and it will make it easier for search engines to index our app. Follow along as Jeremy builds a simple app in React with React Router and then upgrades it with server-side routing.

 Watch Any Course Now

You can take any of our React courses straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to these courses, but also to our growing library of over 1,000 video courses and industry-leading eBooks on Envato Tuts+. 

Plus you now get unlimited downloads from the huge Envato Elements library of 400,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Categories: Web Design

Performant Animations Using KUTE.js: Part 1, Getting Started

Tuts+ Code - Web Development - Mon, 11/20/2017 - 04:00

KUTE.js is a JavaScript-based animation engine which focuses on performance and memory efficiency while animating different elements on a webpage. I have already written a series on using Anime.js to create JavaScript-based animations. This time we will learn about KUTE.js and how we can use it to animate CSS properties, SVG, and text elements, among other things.

Installation

Before we dive into some examples, let's install the library first. KUTE.js has a core engine, and then there are plugins for animating the value of different CSS properties, SVG attributes, or text. You can directly link to the library from popular CDNs like cdnjs and jsDelivr.

<script src="https://cdnjs.cloudflare.com/ajax/libs/kute.js/1.6.2/kute.min.js"></script> <script src="https://cdn.jsdelivr.net/kute.js/1.6.2/kute.min.js"></script>

You can also install KUTE.js using either NPM or Bower with the help of the following commands:

npm install --save kute.js bower install --save kute.js

Once you have included the library in your projects, you can start creating your own animation sequences.

Tween Objects

When creating your animation using KUTE.js, you need to define tween objects. These tween objects provide all the animation-related information for a given element or elements. This includes the element itself, the properties that you want to animate, the duration of the animation, and other attributes like the repeat count, delay, or offset.

You can use the .to() method or the .fromTo() method in order to animate a set of CSS properties from one value to another. The .to() method animates the properties from their default value or their computed/current value to a final provided value. In the case of the .fromTo() method, you have to provide both the starting and ending animation values.

The .to() method is useful when you don't know the current or default value for the property that you want to animate. One major disadvantage of this method is that the library has to compute the current value of all the properties by itself. This results in a delay of a few milliseconds after you call .start() to start the animation.

The .fromTo() method allows you to specify the starting and ending animation values yourself. This can marginally improve the performance of the animations. You can now also specify the units for starting and ending values yourself and avoid any surprises during the course of the animation. One disadvantage of using .fromTo() is that you won't be able to stack multiple transform properties on chained tweens. In such cases, you will have to use the .to() method.

Remember that both .fromTo() and .to() are meant to be used when you are animating individual elements. If you want to animate multiple elements at once, you will have to use either .allTo() or .allFromTo(). These methods work just like their single element counterparts and inherit all their attributes. They also get an extra offset attribute that determines the delay between the start of the animation for different elements. This offset is defined in milliseconds.

Here is an example that animates the opacity of three different boxes in sequence.

The following JavaScript is used to create the above animation sequence:

var theBoxes = document.querySelectorAll(".box"); var startButton = document.querySelector(".start"); var animateOpacity = KUTE.allFromTo( theBoxes, { opacity: 1 }, { opacity: 0.1 }, { offset: 700 } ); startButton.addEventListener( "click", function() { animateOpacity.start(); }, false );

All the boxes above have a box class which has been used to select them all using the querySelectorAll() method. The allFromTo() method in KUTE.js is used to animate the opacity of these boxes from 1 to 0.1 with an offset of 700 milliseconds. As you can see, the tween object does not start the animation by itself. You have to call the start() method in order to start the animation.

Controlling the Animation Playback

In the previous section, we used the start() method in order to start our animations. The KUTE.js library also provides a few other methods that can be used to control the animation playback. 

For example, you can stop any animation that is currently in progress with the help of the stop() method. Keep in mind that you can use this method to stop the animation of only those tween objects that have been stored in a variable. The animation for any tween object that was created on the fly cannot be stopped with this method.

You also have the option to just pause an animation with the help of the pause() method. This is helpful when you want to resume the animation again at a later time. You can either use resume() or play() to resume any animation that was paused.

The following example is an updated version of the previous demo with all the four methods added to it.

Here is the JavaScript code needed to add the start, stop, play, and pause functionality.

var theBoxes = document.querySelectorAll(".box"); var startButton = document.querySelector(".start"); var stopButton = document.querySelector(".stop"); var pauseButton = document.querySelector(".pause"); var resumeButton = document.querySelector(".resume"); var animateOpacity = KUTE.allFromTo( theBoxes, { opacity: 1 }, { opacity: 0.1 }, { offset: 700, duration: 2000 } ); startButton.addEventListener( "click", function() { animateOpacity.start(); }, false ); stopButton.addEventListener( "click", function() { animateOpacity.stop(); }, false ); pauseButton.addEventListener( "click", function() { animateOpacity.pause(); }, false ); resumeButton.addEventListener( "click", function() { animateOpacity.resume(); }, false );

I have changed the animation duration to 2,000 milliseconds. This gives us enough time to press different buttons and see how they affect the animation playback.

Chaining Tweens Together

You can use the chain() method to chain different tweens together. Once different tweens have been chained, they call the start() method on other tweens after their own animation has finished. 

This way, you get to play different animations in a sequence. You can chain different tweens with each other in order to play them in a loop. The following example should make it clear:

var animateOpacity = KUTE.allFromTo( theBoxes, { opacity: 1 }, { opacity: 0.1 }, { offset: 100, duration: 800 } ); var animateRotation = KUTE.allFromTo( theBoxes, { rotate: 0 }, { rotate: 360 }, { offset: 250, duration: 800 } ); opacityButton.addEventListener( "click", function() { animateOpacity.start(); }, false ); rotateButton.addEventListener( "click", function() { animateRotation.start(); }, false ); chainButton.addEventListener( "click", function() { animateOpacity.chain(animateRotation); animateOpacity.start(); }, false ); loopButton.addEventListener( "click", function() { animateOpacity.chain(animateRotation); animateRotation.chain(animateOpacity); animateOpacity.start(); }, false );

We already had one tween to animate the opacity. We have now added another one that animates the rotation of our boxes. The first two buttons animate the opacity and the rotation one at a time. The third button triggers the chaining of animateOpacity with animateRotation. 

The chaining itself doesn't start the animation, so we also use the start() method to start the opacity animation. The last button is used to chain both the tweens with each other. This time, the animations keep playing indefinitely once they have been started. Here is a CodePen demo that shows all the above code in action:

To fully understand how chaining works, you will have to press the buttons in a specific sequence. Click on the Animate Opacity button first and you will see that the opacity animation is played only once and then nothing else happens. Now, press the Animate Rotation button and you will see that the boxes rotate once and then nothing else happens.

After that, press the Chain Animations button and you will see that the opacity animation plays first and, once it completes its iteration, the rotation animation starts playing all by itself. This happened because the rotation animation is now chained to the opacity animation. 

Now, press the Animate Opacity button again and you will see that both opacity and rotation are animated in sequence. This is because they had already been chained after we clicked on Chain Animations.

At this point, pressing the Animate Rotation button will only animate the rotation. The reason for this behavior is that we have only chained the rotation animation to the opacity animation. This means that the boxes will be rotated every time the opacity is animated, but a rotation animation doesn't mean that the opacity will be animated as well. 

Finally, you can click on the Play in a Loop button. This will chain both the animations with each other, and once that happens, the animations will keep playing in an indefinite loop. This is because the end of one animation triggers the start of the other animation.

Final Thoughts

In this introductory KUTE.js tutorial, you learned about the basics of the library. We started with the installation and then moved on to different methods that can be used to create tween objects. 

You also learned how to control the playback of an animation and how to chain different tweens together. Once you fully understand chaining, you will be able to create some interesting animations using this library.

In the next tutorial of the series, you will learn how to animate different kinds of CSS properties using KUTE.js.

Categories: Web Design

Monthly Web Development Update 11/2017: Browser News, KRACK and Vary Header Caching

Smashing Magazine - Fri, 11/17/2017 - 16:14
Editor’s Note: Our dear friend Anselm Hannemann summarizes what happened in the web community in the past few weeks in one handy list, so that you can catch up on everything new and important. Enjoy! Welcome back to our monthly reading list. Before we dive right into all the amazing content I stumbled upon — admittedly, this one is going to be quite a long update — I want to make a personal announcement.
Categories: Web Design

Using CSS Grid: Supporting Browsers Without Grid

Smashing Magazine - Thu, 11/16/2017 - 15:12
When using any new CSS, the question of browser support has to be addressed. This is even more of a consideration when new CSS is used for layout as with Flexbox and CSS Grid, rather than things we might consider an enhancement. In this article, I explore approaches to dealing with browser support today. What are the practical things we can do to allow us to use new CSS now and still give a great experience to the browsers that don’t support it?
Categories: Web Design

Engaging users through high quality AMP pages

Google Webmaster Central Blog - Thu, 11/16/2017 - 08:05

To improve our users' experience with AMP results, we are making changes to how we enforce our policy on content parity with AMP. Starting Feb 1, 2018, the policy requires that the AMP page content be comparable to the (original) canonical page content. AMP is not a ranking signal and there is no change in terms of the ranking policy with respect to AMP.

The open source accelerated mobile pages project (AMP) launched in 2015 and has seen tremendous growth with over 25M domains having implemented the AMP format. This rapid progress comes with a sense of responsibility of ensuring that our users continue to have a great content consumption experience that ultimately leads to more engagement with publisher content.

In some cases, webmasters publish two versions of their content: a canonical page that is not based on AMP and an AMP page. In the ideal scenario, both these pages have equivalent content leading the user to get the same content but with a faster and smoother experience via AMP.  However, in some cases the content on the AMP page does not match the content on its original (canonical) page.

In a small number of cases, AMP pages are used as teaser pages which create a particularly bad user experience since they only contain minimal content. In these instances, users have to click twice to get to the real content. Below is an example of how this may look like: a brief text of the main article and then asking the user to click to visit another page to complete reading the article.

AMP was introduced to dramatically improve the performance of the web and deliver a fast, consistent content consumption experience. In keeping with this goal, we'll be enforcing the requirement of close parity between AMP and canonical page, for pages that wish to be shown in Google Search as AMPs.

Where we find that an AMP page doesn't contain the same critical content as its non-AMP equivalent, we will direct our users to the non-AMP page. This does not affect Search ranking. However, these pages will not be considered for Search features that require AMP, such as the Top Stories carousel with AMP. Additionally, we will notify the webmaster via Search console as a manual action message and give the publisher the opportunity to fix the issue before its AMP page can be served again. The AMP open source website has several helpful guides to help produce fast, beautiful and high-performing AMP pages.

We hope this change encourages webmasters to maintain content parity between the canonical and AMP equivalent. This will lead to better experience on your site and ultimately happier users.


Posted by Ashish Mehta, Product Manager
Categories: Web Design

Dwelling On The Past, Part 2: The Importance Of Self Reflection

Smashing Magazine - Thu, 11/16/2017 - 04:42
Current and aspiring web professionals must continually grow in order to stay relevant. Our field doesn’t allow for stagnation. In part one of this series, I discussed the importance of project retrospectives in facilitating and documenting team growth. We don’t always have the luxury of engaging in team retrospectives, or even of working on teams. Personal reflection provides similar benefits, while focusing on your individual experiences. Personal reflection enables us to process and make meaning of all of the great (and not so great) learning and working experiences we’ve had.
Categories: Web Design

New eBooks Available for Subscribers

Tuts+ Code - Web Development - Wed, 11/15/2017 - 06:11

Do you want to learn more about programming for the Internet of Things? How about mastering object-oriented programming or game development with Swift? Our latest batch of eBooks will teach you all you need to know about these topics and more. What's more, they're all completely free for Envato Elements subscribers to download.

Our Latest Selection of eBooks

This month we’ve made eight new eBooks available for Envato Elements and Tuts+ subscribers to download. Here’s a summary of those books and what you can learn from them.

  • Swift 3 Object-Oriented Programming

    Want to program iOS apps? This book introduces you to the object-oriented paradigm and its implementation in the Swift 3 programming language to help you understand how real-world objects can become part of fundamental reusable elements in the code. 

    You will organize data in blueprints that generate instances. You’ll work with examples so you understand how to encapsulate and hide data by working with properties and access control. Then, you’ll get to grips with complex scenarios where you use instances that belong to more than one blueprint. You’ll discover the power of contract programming and parametric polymorphism. You’ll combine generic code with inheritance and multiple inheritance. Later, you’ll see how to combine functional programming with object-oriented programming and find out how to refactor your existing code for easy maintenance.

  • Swift 3 Game Development

    Swift is the perfect choice for game development. Developers are intrigued by Swift 3.0 and want to make use of new features to develop their best games yet. Packed with best practices and easy-to-use examples, this book leads you step by step through the development of your first Swift game.

    This book starts by introducing SpriteKit and Swift's new features that can be used for game development. After setting up your first Swift project, you will build your first custom class, learn how to draw and animate your game, and add physics simulations.

    Then, you will add the player character, scenes, backgrounds, menus, leaderboards, and much more. By the end of this book, you will be able to create your own iOS games using Swift and SpriteKit.

  • Learning Functional Data Structures and Algorithms

    With the advent of functional programming and with powerful functional languages such as Scala, Clojure and Elixir becoming part of important enterprise applications, functional data structures have gained an important place in the developer toolkit. But how do we express traditional algorithms in functional setting? Won’t we end up copying too much? Do we trade performance for versioned data structures?

    This book attempts to answer these questions by looking at functional implementations of traditional algorithms. By the end of the book, you'll have a solid understanding of functional programming and will be able to write efficient functional data structures and algorithms for your applications.

  • Angular Test-Driven Development

    This is a complete guide that shows you testing techniques with Karma that will help you perform unit testing and end-to-end testing with Protractor. It will show you how to optimize your Angular development process using TDD techniques and ensure your final project is free of bugs. All examples in this book are based on Angular v2 and are compatible with Angular v4.

    You'll start by reviewing the TDD life cycle, TDD in the context of JavaScript, and various JavaScript test tools and frameworks. Then you'll learn to test for multiple classes, partial views, location references, CSS, and the HTML element. Amongst other things, you'll also configure a Karma file to automate the testing and tackle elements of Angular (components, services, classes, and broadcasting) using TDD.

  • Angular Services

    A primary concern with modern-day applications is that they need to be dynamic, and for that, data access from the server side, data authentication, and security are very important. Angular leverages its services to create such state-of-the-art dynamic applications.

    This book will help you create and design customized services, integrate them into your applications, import third-party plugins, and make your apps perform better and faster. This book is up to date for the 2.4 release and is compatible with the 4.0 release as well, and it does not have any code based on the beta or release candidates.

  • Internet of Things Programming With JavaScript

    The Internet of Things (IoT) is an entirely new platform for developers and engineers, but you can use the familiar JavaScript programming language. This book will teach you how to interact with endpoint devices by developing web services in JavaScript and also set up an interface to control all connected devices.

    The book begins with setting up a centralized web server that serves as a hub for all connected devices. It then progresses further towards building web services to facilitate high-level communication between connected devices. Using Arduino and Raspberry Pi Zero as endpoint devices, the book will show you how devices can communicate with each other, perform a wide range of tasks, and also be controlled from a centralized location using JavaScript. You'll end by creating a hybrid app to control the devices that can be run from a browser or installed on a smartphone.

  • Go Design Patterns

    Go is a multi-paradigm programming language that has built-in facilities to create concurrent applications. Design patterns allow developers to efficiently address common problems faced during developing applications.

    Go Design Patterns provides you with a reference point to software design patterns and CSP concurrency design patterns to help them build applications in a more idiomatic, robust, and convenient way in Go.

    The book starts with a brief introduction to Go programming essentials and design patterns. You will then learn how to apply the 23 Gang of Four (GoF) design patterns in Go and also learn about CSP concurrency patterns, the "killer feature" in Go that has helped Google develop software to maintain thousands of servers.

  • Functional PHP

    A functional approach encourages code reuse, greatly simplifies testing, and results in code that is concise and easy to understand. This book will demonstrate how PHP can also be used as a functional language, letting you learn about various function techniques to write maintainable and readable code.

    After a quick introduction to functional programming, you will dive right in with code examples so you can get the most of what you’ve learned. Through the tips and best practices in this book, you’ll be able to do more with less code and reduce bugs in your applications. Not only will you be able to boost your performance, but you will also find out how to eliminate common loop problems. By the end of the book, you will know a wide variety of new techniques that you can use on any new or legacy codebase.

Start Reading With a Combined Subscription

You can take our new course straight away with a subscription to Envato Elements. For a single low monthly fee, you get access not only to these eBooks, but also to our growing library of over 1,000 video courses on Envato Tuts+.

Plus you now get unlimited downloads from the huge Envato Elements library of 400,000+ creative assets. Create with unique fonts, photos, graphics and templates, and deliver better projects faster.

Categories: Web Design

Gates and Policies in Laravel

Tuts+ Code - Web Development - Wed, 11/15/2017 - 04:00

Today, we're going to discuss the authorization system of the Laravel web framework. The Laravel framework implements authorization in the form of gates and policies. After an introduction to gates and policies, I'll demonstrate the concepts by implementing a custom example.

I assume that you're already aware of the built-in Laravel authentication system as that's something essential in order to understand the concept of authorization. Obviously, the authorization system works in conjunction with the authentication system in order to identify the legitimate user session.

If you're not aware of the Laravel authentication system, I would highly recommend going through the official documentation, which provides you with hands-on insight into the subject.

Laravel's Approach to Authorization

By now, you should already know that the Laravel authorization system comes in two flavors—gates and policies. Although it may sound like a complicated affair, I would say it's pretty easy to implement it once you get the hang of it!

Gates allow you to define an authorization rule using a simple closure-based approach. In other words, when you want to authorize an action that's not related to any specific model, the gate is the perfect place to implement that logic.

Let's have a quick look at what gate-based authorization looks like:

... ... Gate::define('update-post', function ($user, $post) { return $user->id == $post->user_id; }); ... ...

The above snippet defines the authorization rule update-post that you could call from anywhere in your application.

On the other hand, you should use policies when you want to group the authorization logic of any model. For example, let's say you have a Post model in your application, and you want to authorize the CRUD actions of that model. In that case, it's the policy that you need to implement.

class PostPolicy { public function view(User $user, Post $post) {} public function create(User $user) {} public function update(User $user, Post $post) {} public function delete(User $user, Post $post) {} }

As you can see, it's a pretty simple policy class that defines the authorization for the CRUD actions of the Post model.

So that was an introduction to gates and policies in Laravel. From the next section onwards, we'll go through a practical demonstration of each element.

Gates

In this section, we'll see a real-world example to understand the concept of gates.

More often than not, you end up looking at the Laravel service provider when you need to register a component or a service. Following that convention, let's go ahead and define our custom gate in the app/Providers/AuthServiceProvider.php as shown in the following snippet.

<?php namespace App\Providers; use Illuminate\Support\Facades\Gate; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Gate::define('update-post', function ($user, $post) { return $user->id == $post->user_id; }); } }

In the boot method, we've defined our custom gate:

Gate::define('update-post', function ($user, $post) { return $user->id == $post->user_id; });

While defining a gate, it takes a closure that returns either TRUE or FALSE based on the authorization logic that's defined in the gate definition. Apart from the closure function, there are other ways you could define gates.

For example, the following gate definition calls the controller action instead of the closure function.

Gate::define('update-post', 'ControllerName@MethodName');

Now, let's go ahead and add a custom route so that we can go through a demonstration of how gate-based authorization works. In the routes file routes/web.php, let's add the following route.

Route::get('service/post/gate', 'PostController@gate');

Let's create an associated controller file app/Http/Controllers/PostController.php as well.

<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; use Illuminate\Support\Facades\Gate; class PostController extends Controller { /* Make sure you don't user Gate and Policy altogether for the same Model/Resource */ public function gate() { $post = Post::find(1); if (Gate::allows('update-post', $post)) { echo 'Allowed'; } else { echo 'Not Allowed'; } exit; } }

In most cases, you'll end up using either the allows or denies method of the Gate facade to authorize a certain action. In our example above, we've used the allows method to check if the current user is able to perform the update-post action.

Users with sharp eyes would have noticed that we've only passed the second argument $post to the closure. The first argument, the current logged-in user, is automatically injected by the Gate facade.

So that's how you're supposed to use gates to authorize actions in your Laravel application. The next section is all about how to use policies, should you wish to implement authorization for your models.

Policies

As we discussed earlier, when you want to logically group your authorization actions for any particular model or resource, it's the policy you're looking for.

In this section, we'll create a policy for the Post model that will be used to authorize all the CRUD actions. I assume that you've already implemented the Post model in your application; otherwise, something similar will do.

The Laravel artisan command is your best friend when it comes to creating stubbed code. You can use the following artisan command to create a policy for the Post model.

$php artisan make:policy PostPolicy --model=Post

As you can see, we've supplied the --model=Post argument so that it creates all the CRUD methods. In the absence of that, it'll create a blank Policy class. You can locate the newly created Policy class at app/Policies/PostPolicy.php.

Let's replace it with the following code.

<?php namespace App\Policies; use App\User; use App\Post; use Illuminate\Auth\Access\HandlesAuthorization; class PostPolicy { use HandlesAuthorization; /** * Determine whether the user can view the post. * * @param \App\User $user * @param \App\Post $post * @return mixed */ public function view(User $user, Post $post) { return TRUE; } /** * Determine whether the user can create posts. * * @param \App\User $user * @return mixed */ public function create(User $user) { return $user->id > 0; } /** * Determine whether the user can update the post. * * @param \App\User $user * @param \App\Post $post * @return mixed */ public function update(User $user, Post $post) { return $user->id == $post->user_id; } /** * Determine whether the user can delete the post. * * @param \App\User $user * @param \App\Post $post * @return mixed */ public function delete(User $user, Post $post) { return $user->id == $post->user_id; } }

To be able to use our Policy class, we need to register it using the Laravel service provider as shown in the following snippet.

<?php namespace App\Providers; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; use Illuminate\Http\Request; use App\Post; use App\Policies\PostPolicy; class AuthServiceProvider extends ServiceProvider { /** * The policy mappings for the application. * * @var array */ protected $policies = [ 'App\Model' => 'App\Policies\ModelPolicy', Post::class => PostPolicy::class ]; /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); } }

We've added the mapping of our Policy in the $policies property. It tells Laravel to call the corresponding policy method to authorize the CRUD action.

You also need to register the policies using the registerPolicies method, as we've done in the boot method.

Moving further, let's create a couple of custom routes in the routes/web.php file so that we can test our Policy methods there.

Route::get('service/post/view', 'PostController@view'); Route::get('service/post/create', 'PostController@create'); Route::get('service/post/update', 'PostController@update'); Route::get('service/post/delete', 'PostController@delete');

Finally, let's create an associated controller at app/Http/Controllers/PostController.php.

<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller; use App\Post; use Illuminate\Support\Facades\Auth; class PostController extends Controller { public function view() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('view', $post)) { echo "Current logged in user is allowed to update the Post: {$post->id}"; } else { echo 'Not Authorized.'; } } public function create() { // get current logged in user $user = Auth::user(); if ($user->can('create', Post::class)) { echo 'Current logged in user is allowed to create new posts.'; } else { echo 'Not Authorized'; } exit; } public function update() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('update', $post)) { echo "Current logged in user is allowed to update the Post: {$post->id}"; } else { echo 'Not Authorized.'; } } public function delete() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('delete', $post)) { echo "Current logged in user is allowed to delete the Post: {$post->id}"; } else { echo 'Not Authorized.'; } } }

There are different ways you could authorize your actions using Policies. In our example above, we’ve used the User model to authorize our Post model actions.

The User model provides two useful methods for authorization purposes—can and cant. The can method is used to check if the current user is able to execute a certain action. And the counterpart of the can method, the cant method, is used to determine the inability of the action execution.

Let’s grab the snippet of the view method from the controller to see what exactly it does.

public function view() { // get current logged in user $user = Auth::user(); // load post $post = Post::find(1); if ($user->can('view', $post)) { echo "Current logged in user is allowed to update the Post: {$post->id}"; } else { echo 'Not Authorized.'; } }

Firstly, we load the currently logged-in user, which gives us the object of the User model. Next, we load an example post using the Post model.

Moving ahead, we’ve used the can method of the User model to authorize the view action of the Post model. The first argument of the can method is the action name that you want to authorize, and the second argument is the model object that you want to get authorized against.

That was a demonstration of how to use the User model to authorize the actions using policies. Alternatively, you could use the Controller Helper as well, if you’re in the controller while authorizing a certain action.

… $this->authorize('view', $post); …

As you can see, you don’t need to load the User model if you use the Controller Helper.

So that was the concept of policies at your disposal, and it’s really handy while authorizing a model or a resource as it allows you to group the authorization logic in one place.

Just make sure that you don’t use gates and policies altogether for the same actions of the Model, otherwise it’ll create issues. That’s it from my side for today, and I’ll call it a day!

Conclusion

Today, it was Laravel authorization that took the center stage in my article. At the beginning of the article, I introduced the main elements of Laravel authorization, gates and policies.

Following that, we went through creating our custom gate and policy to see how it works in the real world. I hope you’ve enjoyed the article and learned something useful in the context of Laravel.

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study on Envato Market.

As always, I would love to hear from you in the form of comments using the feed below!

Categories: Web Design

Make your site's complete jobs information accessible to job seekers

Google Webmaster Central Blog - Wed, 11/15/2017 - 03:00

In June, we announced a new experience that put the convenience of Search into the hands of job seekers. Today, we are taking the next step in improving the job search experience on Google by adding a feature that shows estimated salary information from the web alongside job postings, as well as adding new UI features for users.

Salary information has been one of the most requested additions from job seekers. This helps people evaluate whether a job is a good fit, and is an opportunity for sites with estimated salary information to:

  • Increase brand awareness: Estimated salary information shows a representative logo from the estimated salary provider.
  • Get more referral traffic: Users can click through directly to salary estimate pages when salary information surfaces in job search results.

If your site provides salary estimates, you can take advantage of these changes in the following ways:

Specify actual salary information

Actual salary refers to the base salary information that is provided by the employer. If your site publishes job listings, you can add JobPosting structured data and populate the baseSalary property to be eligible for inclusion in job search results.

This salary information will be made available in both the list and the detail views.

Provide estimated salary information

In cases where employers don’t provide actual salary, job seekers may see estimated salaries sourced from multiple partners for the same or similar occupation. If your site provides salary estimate information, you can add Occupation structured data to be eligible for inclusion in job search results.  

Include exact location information

We've heard from users that having accurate, street-level location information helps them to focus on opportunities that work best for them. Sites that publish job listings can do this can do this by using the jobLocation property in JobPosting structured data.

Validate your structured data

To double-check the structured data on your pages, we'll be updating the Structured Data Testing Tool and the Search Console reports in the near future. In the meantime, you can monitor the performance of your job postings in Search Analytics. Stay tuned!

Since launching this summer, we’ve seen over 60% growth in number of companies with jobs showing on Google and connected tens of millions of people to new job opportunities. We are excited to help users find jobs with salaries that meet their needs, and to route them to your site for more information. We invite sites that provide salary estimates to mark up their salary pages using the Occupation structured data. Should you have any questions regarding the use of structured data on your site, feel free to drop by our webmaster help forums.


Posted by Nick Zakrasek, Product Manager
Categories: Web Design

Pages