Pagination in CodeIgniter: The Complete Guide

The benefit of using any full-stack web application framework is that you don’t have to worry about the common tasks like input handling, form validation and the like, as the framework already provides wrappers for those features. Thus, it allows you to concentrate on the business logic of the application rather than reinventing the wheel over and over again.

Today, we’re going to explore an important library in the CodeIgniter framework—the pagination library.

Let me highlight the topics that we’re going to cover in the course of this article:

  • Demonstration of basic paging
  • Explore the customization options
  • Pagination configuration

Demonstration of Basic Paging

In this section, we’ll go through an example that demonstrates the use of pagination in CodeIgniter. It’s the best way to understand how things work altogether.

In our example, we’ll build a pretty simple user listing in which we’ll fetch records from the users MySQL table. In order to successfully run this example, make sure that you have the uid and uname fields in your users table.

With that set up, we’re ready to roll.

Go ahead and create a controller file controllers/Paging.php with the following contents.

Next, we’ll need a model file models/Users.php that fetches records from the users table.

Finally, let’s create a view file at views/user_listing.php that displays the user listing.

Now, go ahead and access our custom page at http://your-code-igniter-site/paging/index and you should see the user listing along with the pagination! So, that’s it, we’ve done it! Don’t worry, I won’t leave you that soon, as we’ll start dissecting each part of the code now.

We’ll start with the model file models/Users.php as that’s something will be called from our controller methods. There are two important methods, get_current_page_records and get_total, that our model implements in order to build the pagination links.

Let’s go through the get_total method. It’s used to count the number of records in the users table.

Next, there’s a get_current_page_records method.

There are two important arguments that you should note in the get_current_page_records method. The first argument, $limit, is used to specify the number of records that will be returned during the query run. And the second argument, $start, acts as the starting index of the record.

So, as you can see, given the values of $start and $limit we can fetch records by page. That’s the essence of paging, and meanwhile we’ve implemented the most important method of this article!

So, that was our model—simple and elegant!

Moving ahead, let’s switch our attention to the controller file. Go ahead and grab the code of the constructor method.

In order to use pagination in CodeIgniter, the first thing you need to do is to load the pagination library. And we can do it by using $this->load->library('pagination').

We’ve also loaded the URL helper so that we can use global helper functions provided by that helper.

Now, we’re ready to go through the heart of our controller—the index method.

To start with, we make sure that the database is loaded properly. Following that, we load the Users model so that we can use the model methods.

Next, we initialize a couple of important variables.

The variable $limit_per_page defines the limit per page. Of course, you could set it as you wish; it’s set to 1 at the moment for example purposes.

The $start_index variable holds the starting index of the MySQL record. When CodeIgniter builds the pagination links, it appends the starting index of the page as the third segment in the URL by default. You can change this default behavior, but that’s something we’ll reserve for the last section of this article, where we’ll discuss customization options.

Finally, we call the get_total method of the Users model to get the total records of the users table, and it’s assigned to the $total_records variable.

Next, we fetch the records of the current page using the get_current_page_records method.

Before we can actually go ahead and build pagination links, we need to initialize the minimal paging configuration using the initialize method of the paging library.

And that’s the set of minimum parameters to build the pagination links.

  • base_url: The URL that will be used while building pagination links
  • total_rows: Total number of records
  • per_page: Record count per page

Finally, we use the create_links method to build pagination links.

The rest is just the formality to call our view user_listing and render the output! Run the URL http://your-code-igniter-site/paging/index to see the user listing along with the pagination links.

So that’s a very simple yet useful pagination example at your disposal that you could extend to fit your requirements.

In the next section, we’ll explore how you could customize the default pagination in terms of appearance and functionality.

Explore Customization Options

In this section, we’ll explore the options available that you could use should you wish to customize the default pagination links.

URI Segment

Although the CodeIgniter paging library automatically detects the paging-related parameter from the URL, you could define a custom value if you have different URL pattern.

Number of Digit Links

The num_links option allows you to define the number of digit links that will be displayed before and after the active page number in the pagination links.

Page Number as URI Segment

When you access the paging URI segment, it’s a starting index by default. For example, if you have ten records per page, the paging URI segment is 20 for the third page. Instead, if you want to show actual page numbers in the paging links, you can set use_page_numbers to TRUE.

Of course, you need to make sure that you calculate the proper starting index based on the page number you retrieve from the URL.

Preserve Query String

More often than not, you end up in the situation where you want to preserve query string parameters that are not related to pagination. You can use the reuse_query_string option to enable that facility.

These were a few options that you could use to alter the default pagination functionality. Next, we’ll look at a couple of other options that allow you to alter the way pagination links are displayed.

Wrapper Tag

If you want to wrap the pagination code with any other HTML tag then you could do it using the full_tag_open and full_tag_close options.

It could be really useful should you wish to apply custom styling to the pagination links.

First, Last, Next, and Previous

If you want to change the text that will be displayed for the first, last, next and previous links, you could do that as well.

Also, if you want to wrap those individual links with any HTML tag, you could do that in the same way as we did it to wrap the whole paging code.

Active Link and Number Link

Sometimes, you want to style the active link differently. You could do that by applying wrapper tags as shown below.

In the same way, if you want to wrap digit links with something:

And that ends the story of customization. In fact, you could go ahead and look at the customization example at http://your-code-igniter-site/paging/custom that’s already included in our controller file!

Paging Configuration

Now you’re aware of the configuration that’s required to set up a decent pagination with any model listing. And most of the time, you want to keep it the same throughout the site. What are you going to do to achieve that? You might be tempted to copy the configuration code and paste it into each action that requires the pagination configuration.

In fact, there’s a better way you could handle this scenario. You can create a paging configuration file at application/config/pagination.php and use the $config variable to define your settings.

Based on that, the revised index action method should look like this:

Of course, the total_rows and base_url variables change from action to action, so you need to set them explicitly in every action.

To accomplish that, you need to load the pagination configuration in the first place.

Next, you can override the action specific settings.

And you’re done with that!

So that was the story of the pagination configuration, and that ends this article as well!

Conclusion

Today, we went through the pagination library in CodeIgniter.

In the first part of this article, I demonstrated how you can use the pagination library by providing a very simple yet useful example.

Following that, we discussed the customization options that are available at your disposal while setting up the pagination.

Finally, we discussed the pagination configuration in the last section.

CodeIgniter is a powerful PHP platform. Whether you’re just getting started or you’re starting with the next version, don’t forget to check out what we have available for you, as well.

I would love to know your feedback in the form of queries and comments using the feed below!


Source: Nettuts Web Development

JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG

After completing the first three tutorials of the series, you should now be very comfortable with a lot of Anime.js features. The first tutorial showed you how to select target elements. In the second tutorial, you learned about different types of parameters that can be used to have fine control over the delay and duration of animations of different elements. The third tutorial focused on learning how to have greater control over the values of a single property during the course of the animation.

In this tutorial, you will learn about different callbacks that can be used to execute a function based on the progress of the animation. Almost every example in the previous tutorials used CSS properties to demonstrate how different methods and parameters work. This might have given you the idea that the library is more suited for animating CSS properties. This time, we will have a section dedicated to the creation of interesting SVG-related animations in Anime.js.

Callbacks

As I mentioned in the introduction, you can use callbacks to execute functions based on the progress of the animation. There are four different callbacks: begin, run, update, and complete. Each callback function is fired at a specific time, and each one accepts an animation object as its argument. 

The begin() function is called when the animation actually begins. This means that if an animation has a delay of 800ms, begin() will be called only after that delay is over. You can check if an animation has begun playing or not using animationName.begin, which will return true or false respectively.

The run callback can be used to execute a function in every frame after an animation actually starts playing. If you want to execute a function in every frame from the very beginning of the animation irrespective of its delay, you should use the update callback instead.

The complete callback is similar to begin except for the fact that it is called once the animation has finished playing. Just like begin, you can use animationName.complete to check if an animation has finished playing or not.

You have already seen in the first tutorial how to use the update callback while animating numerical values of a JavaScript object. In this tutorial, we will modify that example and see how to use all these callbacks together to provide more information to the user.

I have intentionally added some delay in this animation so that we can notice the difference in the timing of the execution of different callbacks. The update callback starts executing its function as soon as the animation instance begins. 

The actual animation starts playing after 1000ms, and that’s when the begin function shows its “Starting the Scan…” message to the user. The run function also starts executing at the same time and updates the numerical values of the object after every frame. Once the animation has finished, the complete callback shows a “Scan Complete…” message to the user.

Easing Functions

Easing functions can be used to control how the value of a property transitions from its initial value to its final value. These easing functions can be specified using the easing parameter, which can accept strings as well as custom Bézier curve coordinates (in the form of an array). 

There are 31 different built-in easing functions. One of them is linear, and the other 30 consist of ten different variations of easeIn, easeOut, and easeInOut. There are three elastic easing equations called easeInElasticeaseOutElastic, and easeInOutElastic. You can control their elasticity using the elasticity parameter. The value of elasticity can be anywhere between 0 and 1000.

EaseIn equations accelerate the value change of the property starting from zero. This means that the change in value would be slow in the beginning and very quick at the end. The rate of change is zero in the beginning and maximum at the end. EaseOut equations decelerate the value change of the property starting from the maximum rate change. 

This means that the change in value would be very quick in the beginning and very slow at the end. EaseInOut equations accelerate the rate change in the beginning and decelerate it at the end. This means that the rate of change will be slow in the beginning as well as the end, and it will be fastest in the middle of the animation. The following demo shows the difference in the rate of change for each of these easing functions.

You can also add your own custom easing functions to the built-in list with the help of anime.easings. Here is an example of creating custom easing functions.

SVG-Based Animations

All the motion-related animations that we have created until now moved the target elements in straight lines. It is also possible in Anime.js to move an element along a complex SVG path with lots of curves. You can control both the position and the angle of the animating elements on the path. To move an element to the x coordinate of the path, you can use path(x). Similarly, an element can be moved according to the y coordinate of the path using path(y)

Unless the path is a straight line, it will almost always form an angle with respect to the horizontal base line. If you are rotating any non-circular element, it will feel more natural if the element follows the angle of the path. You can do so by setting the rotate property to be equal to path('angle'). Here is the code that animates four elements with different easing values along an SVG path.

You can see in the following demo that the red square with easeInCubic easing is slowest in the beginning and the fastest at the end. Similarly, the orange square with easeOutCubic is the fastest in the beginning and the slowest at the end.

You can also animate the morphing of different SVG shapes into one another using Anime.js. The only condition is that both the shapes should have the same number of points. This means that you can only morph triangles into other triangles and quadrilaterals into other quadrilaterals. Trying to morph between an unequal number of polygon points will result in an abrupt shape change. Here is an example of morphing a triangular shape.

One more interesting effect that you can create with SVG is line drawing. All you have to do is give Anime.js the path that you want to use for line drawing and other parameters that control its duration, delay, or easing. In the following demo, I have used the complete callback to fill the line drawing of the Font Awesome anchor icon with a yellow color.

Combining the knowledge of all the concepts that you have learned so far, you can create more complex line drawings with much better control over the way they are drawn. Here is an example in which I have written my own name using SVG.

I begin by assigning the value 2000 to the variable letterTime. This is the time that I want Anime.js to take while it draws each letter of my name. The delay property uses the function-based index parameter to set an appropriate delay value with the help of the letterTime variable. 

The index of the first letter “M” is zero, so Anime.js starts drawing it immediately. The letter “O” has a delay of 2000ms because that’s the amount of time it takes to completely draw the letter “M”.

Inside the begin callback, I have set the stroke value of all the letters to black and their fill values to none. This way we can clear all the color values applied inside the update callback so that the letters can return to their initial state when run in multiple loops. Try clicking the Write the Name button in the following demo to see the code in action.

Final Thoughts

In this tutorial, you learned about different callback functions that can be used to perform tasks like updating the DOM or changing the value of an attribute based on the animation progress. You also learned about different easing functions and how to create one of your own. The final section of the tutorial focused on creating SVG-based animations.

After completing all four tutorials of the series, you should now have enough knowledge of Anime.js to create some interesting effects for your next project. If you have any questions related to this tutorial, please let me know in the comments.


Source: Nettuts Web Development

JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback

In the previous tutorial of the Anime.js series, you learned about different kinds of parameters that control how different target elements should be animated. You also learned how to use function parameters to gradually change the delay or duration of the elements. 

In this tutorial we will go a step further and learn how to specify the property values themselves using regular numbers, function-based values, and keyframes. You will also learn how to play animations in sequence using timelines.

Specifying Property Values

Anime.js allows you to specify the final or end values for animatable properties of target elements. The initial or start value for the animation is the default value of that property. Any value specified in the CSS can also act as the start value. There are multiple ways of specifying an end value. 

It can also be a unitless number. In this case, the original or default units of the property are used while calculating any property values. You can also specify the value as a string, but the string must contain at least one numerical value. Examples of string values would be 10vh, 80%, and 9.125turn.

Instead of specifying an absolute value, you can also specify property values relative to their current value. For example, you can set the final translateY value to be 150px greater than the current value using +=150px as a value. Keep in mind that you can only use addition, multiplication and subtraction while specifying relative values.

While animating colors, you cannot use color names like red, black and blue to set a final color value for the animation. In such cases, the color animation won’t happen at all, and the change will be instant. The only way to animate colors is to specify the values either as hex digits or in terms of RGB and HSL values.

As you might have noticed, we have not been specifying an initial value for our target elements to animate them. Anime.js automatically determines the initial value based on our CSS and the default values of those properties. However, you can specify an initial value other than the default value for a property using arrays. The first item in the array signifies the initial value, and the second item signifies the final value.

Instead of using the same final value for all your target elements, you can use functions to set different values for different parameters. The process is similar to specifying function-based property parameters.

For the translateY property, we are using the index of the element to set a translation value. Using 50 * (i + 1) increases the translateY value for each element by 50 pixels. 

The scaling animation also uses the index of the element along with the built-in Math.random() function to return a floating-point, pseudo-random number less than 1. This way the elements scale randomly, but the i/10 part of the property slightly increases the possibility of elements that occur in the end having a larger size.

Inside the code for rotation animation, we are using the anime.random(a, b) helper function to get random integers between -180 and 180. This function is helpful for assigning random integral values to properties like translateY and rotate. Using this function to assign random scale values will produce extreme results.

The border radius value for different elements is determined by calculating the width of target elements using the el function parameter. Finally, the last part of code assigns random values to the duration and delay parameters as well. 

You can see that the animation achieved by the last part is very random. There is no relation between the values of different properties of elements or their delay and duration values. In real life, it is more sensible to use values that can add some sense of direction to the animation.

It is also possible to animate different properties of your target elements using keyframes. Each keyframe consists of an array of the property object. You can use the object to specify the property value, duration, delay and easing for that part of the animation. The following code creates a keyframe-based translation animation.

You can also animate multiple properties at once by specifying different or the same values for all the parameters. In the second case, the global delay parameter applies an initial delay to all the elements based on their index. This delay is independent of the delay applied to each property inside the keyframes.

Creating and Manipulating Timelines

So far in the series, we have been using the delay parameter to play different animations in a specific sequence. To use delay for this purpose, we also need to know the duration of the previous animation. 

With the increasing complexity of the animation sequence, maintaining the right delay value becomes very tedious. Any change in the duration of one of the animations will force us to recalculate all the delay values to keep the animations in the original sequence.

A better solution to this problem is using timelines to control the animation sequence. You have to use the anime.timeline() function to create a timeline in Anime.js. You can also pass different parameters to this function as an object. These parameters can specify the direction in which the timeline is played, the number loops, and an autoplay parameter to determine if the animation should be auto-played. All these parameters have been discussed in detail in the parameters tutorial of this series.

You can add different animations to a timeline using the add() method. All the animations added to the timeline will be played in the order in which they were added. It is possible to specify absolute or relative offset values to control the order in which the animations are played. 

When relative offset values are used, the starting time of the current animation is determined relative to the timing of the previous animation. Relative offsets can be of three types:

  • +=offset: In this case, the current animation starts playing after offset number of milliseconds have passed since the end of the previous animation.
  • -=offset: In this case, the current animation starts playing offset number of milliseconds before the end of the previous animation.
  • *=offset: In this case, the current animation starts playing after milliseconds equal to offset times the animation duration of the previous animation have passed.

The following code shows how to create a basic timeline and a timeline with relative offset values.

Try clicking the Offset Timeline button in the above demo. You will see that there is a delay of 2 seconds between the end of the animation of red squares and the beginning of the animation of blue squares. 

We have not specified a duration for the red square animation. Therefore, a default value of 1000ms or 1s is used as duration. The multiplier offset of the blue square animation doubles that value, and this results in a delay of two seconds in the animation.

When absolute offset values are used, the starting time of the timeline is used as a reference point. It is possible to reverse the sequence in which the animations are played by using large offset values for animations that occur at the beginning of the timeline.

Playback Options

Anime.js has a variety of options to play, pause, restart or seek animations or timelines at any given point.

The play() function allows us to start the animation from its current progress. The pause() function will freeze the animation at the moment the function was called. The restart() function starts the animation from the beginning, irrespective of its current progress. The seek(value) function can be used to advance the animation by value number of milliseconds.

You should keep in mind that the play() function only resumes the animation from the time it was paused. If the animation has already reached its end, you cannot replay the animation using play(). To replay the animation, you will have to use the restart() function.

Note that we are not using seekInput.value to set a value for the seek function. This is because the max value for the range input has been set to 100 in the markup. Directly using the value for input range will allow us to only seek up to 100ms. Multiplying the range input value with the animation duration makes sure that we can seek the animation from the beginning to the end on our range slider.

Final Thoughts

In this tutorial, you learned how to animate different property values as numbers, functions, or keyframes. You also learned how to control and manipulate timelines in Anime.js to control the order in which an animation sequence is played.

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

If you have any questions related to this tutorial, please let me know in the comments.


Source: Nettuts Web Development

JavaScript-Based Animations Using Anime.js, Part 2: Parameters

In the first tutorial of the Anime.js series, you learned about different ways of specifying the target elements that you want to animate and the kinds of CSS properties and DOM attributes that can be animated. The animations in the previous tutorial were very basic. All the target elements were just moving a certain distance or changing the border radius at a fixed speed. 

Sometimes, you might need to animate the target elements in a more rhythmic manner. For example, you might have ten different elements that you want to move from left to right with a delay of 500ms between the start of the animation for each element. Similarly, you might want to increase or decrease the animation duration for each element based on its position.

In this tutorial, you will learn how to use Anime.js to properly time the animation of different elements using specific parameters. This will allow you to control the order in which an animation sequence is played for individual elements or all the elements.

Property Parameters

These parameters allow you to control the duration, delay and easing of individual properties or a group of properties at once. The duration and delay parameters are specified in milliseconds. The default value for duration is 1000ms or 1s. 

This means that unless specified otherwise, any animation applied to an element will be played for 1 second. The delay parameter specifies the amount of time the animation takes to begin once you have already triggered it. The default value for delay is 0. This means that the animations will begin as soon as they are triggered.

You can use the easing parameter to control the rate at which an animation is played for the duration it is active. Some animations start out slow, pick up pace in the middle, and then slow down again at the end. Others start at a good pace and then slow down for the rest of the time. 

However, in all the cases, the animation always completes within the time specified using the duration parameter. Anime.js provides a lot of easing functions that you can apply to your elements directly by only using their names. For some easing functions, you can also set a value for the elasticity parameter to control how much an element’s value bounces back and forth like a spring. 

You will learn more about different easing functions in the final tutorial of the series. The following code snippet shows how to apply all these parameters to different animations.

As you can see, these parameters can be used independently of other parameters or in combination with them. The cubicAnimation has both the duration and easing parameter applied to it. If the duration had not been specified, the animation would have run for 1 second. Now, it will run for 1,200 milliseconds or 1.2 seconds.

One major limitation of property parameters in the above example was that all the animations of the target element will have the same duration, delay and easing values. 

This may or may not be the desired behavior. For example, instead of translating and changing the border radius of the target element at the same time, you might want to first translate the target element and then animate its border radius. Anime.js allows you to specify different values for the duration, delay, easing and elasticity parameters for individual properties. The following code and demo should make it clearer.

In the above code, all the properties that we want to animate have different values. The background color animation has a duration of 400ms, while the rotation and translation animations use the global duration value of 1500ms. 

The background color animation also has a delay so any change in the color only starts after 1500ms have passed. The rotate and translateY properties use the default value for the delay and easing parameters because we have neither provided a local nor a global value for them.

Function-Based Parameters

Property-based parameters are helpful when you want to change the order and duration for animating individual properties. However, the same duration and delay will still be applied for individual properties on all the target elements. Function-based parameters allow you to separately specify the duration, delay, elasticity and easing for different target elements in a compact manner. 

In this case, you set the values of different parameters using functions instead of numbers. These functions accept three parameters: target, index, and targetCount. The target parameter stores the reference to the current target element. The index parameter stores the index or position of the current target element. The targetCount parameter stores the total number of target elements.

The target parameter is useful when the animation values need to be set based on some attributes of the target element. For example, you can store the delay, duration or easing values for a target element in data attributes and then access them later. 

Similarly, you could access the background color of a target element and then manipulate it to set a final unique color value for individual elements. In this way, you could animate all the elements to have a background color that is 20% darker than their current color.

The index parameter gives you the position of the current target in our list of target elements. You can use it to gradually change the value for parameters like duration and delay for different elements. 

This is generally useful when you want to set the values in ascending order. You can also subtract the index from the targetCount to set the values in descending order. The following code snippet uses both these parameters to specify the values in ascending and descending order.

The following code sets a different easing value for each target element using the index parameter.

Animation Parameters

This last set of parameters allows you to specify the number of times an animation should be played and the direction in which it should be played. You can specify the number of times an animation should be played using the loop parameter. There is also an autoplay parameter which can be set to true or false. Its default value is true, but you can stop the animations from starting by themselves by setting it to false.

The direction parameter controls the direction in which the animation is played. It can have three values: normal, reverse, and alternate. The default value is normal, which keeps the animation playing normally from the start values to the finish values. Once the target elements reach the finishing value, if the loop value is greater than 1, the target elements jump back abruptly to the start values and then begin the animation again.

When the direction is set to reverse and the loop value is greater than 1, the animation gets reversed. In other words, the target elements start the animation from their final state and go backwards to reach the initial state. Once they are in the initial state, the elements jump back to the final state and then again start the reverse animation. The alternate direction value changes the animation direction after every loop.

In the following demo, I have set the number of loops to four so that you can easily notice the difference in animation of the elements in different modes.

Final Thoughts

In this tutorial, you learned about different kinds of parameters that can be used to control the animation of target elements in Anime.js. The property parameters are used to control the animation of individual properties. 

You can use them to control the sequence in which the animation is played for individual elements. The function parameters allow you to control the timing and rate of animation for individual elements with respect to the whole group. The animation parameters allow you to control how the animation itself is played for different elements.

If you have any questions related to this tutorial, please let me know in the comments.


Source: Nettuts Web Development

JavaScript-Based Animations Using Anime.js, Part 1: Targets and Properties

Anime.js is a lightweight JavaScript-based animation library. You can use it to animate different CSS properties, SVG or DOM attributes on a webpage. The library allows you to control all aspects of the animation and provides a lot of ways for you to specify the elements that you want to target or the properties that you want to animate. 

You have full control over the sequence in which the animations are played or how synchronized the animations of different elements are with respect to each other. The library supports all modern browsers, including IE10+. 

In this tutorial series, you will learn about all the features of Anime.js so that you can use them in real-life projects with ease.

Before diving deep into the topic, let’s install the library first. You can use either npm or bower to perform the installation by running the following commands:

You can also download the library and include it in your project or directly link to the latest version of the library hosted on a CDN.

After a successful installation, you are now ready to use this library to add interesting animation to your elements. We will start with the basics of the library, focusing on one particular area at a time.

Specifying Target Elements

To create any animations using Anime.js, you will have to call the anime() function and pass it an object with key-value pairs that specify the target elements and properties that you want to animate, among other things. You can use the targets key to tell Anime.js which elements you want to animate. This key can accept values in different formats.

CSS Selectors: You can pass one or more CSS selectors as a value for the targets key. 

In the first case, Anime.js will animate all the elements with a blue class. In the second case, Anime.js will animate all the elements with either the red or blue class. In the third case, Anime.js will animate all the even children with a square class. In the last case, Anime.js will animate all the elements with a square class that don’t have a red class.

DOM Node or NodeList: You can also use a DOM node or a NodeList as a value for the targets key. Here are a few examples of setting the targets as a DOM node.

In the first case, I have used the getElementById() function to get our special element. The querySelector() function is used to get the first element that has the blue class. The querySelectorAll() function is used to get all the elements within the document that match the specified group of selectors. 

There are a lot of other functions as well that you can use to select your target elements that you want to animate. For example, you can get all the elements with a given class name using the getElementsByClassName() function. Similarly, you can also get all the elements with a given tag name using the getElementsByTagName() function. 

Any function that returns a DOM node or a NodeList can be used to set the value of the targets key in Anime.js.

Object: You can also use a JavaScript object as a value for the targets key. The key of that object is used as an identifier, and the value is used as a number that needs to be animated. 

You can then show the animation inside another HTML element with the help of additional JavaScript. Here is the code to animate the values of two different keys of an object.

The above code will animate the scanned files count from 0 to 1,000 and the infected files count from 0 to 8. Keep in mind that you can only animate numerical values this way. Trying to animate a key from ‘AAA’ to ‘BOY’ will result in an error. 

We have also used a callback function for the update key that is called on every frame while the animation is running. We have used it here to update the count of scanned and infected files. However, you could go a step further and show users an error message when the number of infected files goes over a certain threshold. 

Array: The ability to specify a JavaScript array as the target comes in handy when you have to animate a bunch of elements that fall under different categories. For example, if you want to animate a DOM node, an object and a bunch of other elements based on CSS selectors, you can do so easily by putting all of them inside an array and then specifying that array as a value for the targets key. The following example should make it clearer:

Properties That Can Be Animated in Anime.js

Now that you know how to specify different elements that you want to animate, it is time to learn about all the properties and attributes that can be animated using the library.

CSS Properties: Anime.js lets you animate a lot of CSS properties, like the width, height, and color, for different target elements. The final values of different animatable properties like background-color and border-width are specified using a camel case version of that property. Therefore, background-color becomes backgroundColor, and border-width becomes borderWidth. The following code snippet shows how to animate the left position and the background color of a target element in Anime.js.

The properties can accept all kinds of values that they would have accepted when used in regular CSS. For example, the property left could be set to 50vh, 500px, or 25em. You could also specify the value as a bare number. In this case, the number would be converted to a pixel value. Similarly, the background color could be specified as a hexadecimal, RGB or HSL color value.

CSS Transforms: You can also animate different CSS transform properties using Anime.js. Translation along the x and y axes can be achieved using the translateX and translateY properties. Similarly, it is possible to scale, skew or rotate an element along a specific axis by using the scale, skew and rotate property corresponding to that specific axis. 

You can specify different angles either in terms or degrees or in terms of turn. The value of 1 turn is equal to 360°. This can make the calculation easier when you know how much you want to turn the elements in terms of complete rotations. The following example shows how to animate the scaling, translation or rotation of an element on an individual basis as well as all at once.

SVG Attributes: It is possible to animate attributes of different SVG elements using Anime.js. The only condition is that the value of those attributes should be numerical. This ability to animate different attributes opens up the possibility of creating some really cool effects. Since you are just starting to learn about Anime.js, we will keep the examples in this tutorial very basic. 

As we move forward, you will learn how to create more complex animations. Here is the code to animate the cx, cy and stroke-width attributes of a circle. Just like the CSS properties, you need to use a camel case version of stroke-width for the code to work.

DOM Attributes: You can also animate numerical DOM attributes just like you animated the SVG attributes. One situation where animating a DOM attribute can be useful is the HTML5 progress element. This element has two attributes, value and max. In our example, we will be animating the value attribute to show the progress of our file transfer process. Here is the code to animate the value attribute.

Final Thoughts

In this tutorial, you learned about all the ways of selecting target elements in Anime.js and how to animate different CSS properties and attributes related to them. At this point, we are not controlling anything related to the actual animation. 

JavaScript is arguably the language of the web. It’s not without its learning curves, of course, and there are plenty of frameworks and libraries to keep you busy, as you can tell. If you’re looking for additional resources to study or to use in your work, check out what we have available in the Envato marketplace.

In the next tutorial of the series, you will learn how to control the easing, delay and duration of the animation for different properties as a group as well as individually. You will then learn how to control all these animation parameters for individual elements.

If there are any questions related to this tutorial or if you have used Anime.js in any interesting projects, please let us know in the comments.


Source: Nettuts Web Development

20 Popular WordPress User Interface Elements

A user interface (UI) is defined as “the means by which the user and a computer system interact, in particular the use of input devices and software.” It is one of the more important web design concepts but is often overlooked.

Having a good user interface ensures website visitors can find what they are looking for, do what they came to do, and most importantly, stay on your website. The moment that your website user interface becomes difficult to use is the moment when the user takes their browser elsewhere.

In an effort to help you provide the best interface, let’s take a look at 20 popular WordPress user interface elements that are sure to help you make your website user-friendly.

1. Responsive FlipBook Plugin

Deliver web content within a beautiful UI with this incredible WordPress plugin.

At first glance, the Responsive FlipBook Plugin looks like a nice way to display content with its cool bookshelf design.

But it’s so much more.

Responsive FlipBook Plugin

“Create any FlipBook with ease. Comes with: bookshelf, zoom, print, PDF to FlipBook, table of content, hard covers, flat design, custom styles, lazy load.”

Features include:

  • mobile zoom
  • PDF Wizard
  • easy print
  • lazy load
  • and more!

Create and present a complete collection of online based eBooks with the Responsive FlipBook Plugin.

It’s pretty amazing.

2. Content Timeline – Responsive WordPress Plugin for Displaying Posts/Categories in a Sliding Timeline

This WordPress user interface is unique, and I love it!

The Content Timeline – Responsive WordPress Plugin for Displaying Posts/Categories in a Sliding Timeline is the perfect solution for a large array of content presentation types.

Content Timeline - Responsive WordPress Plugin for Displaying PostsCategories in a Sliding Timeline

Included features:

  • fully responsive with SWIPE function
  • 7 embedded script control methods
  • 11 settings for easy customization
  • keyboard bindings
  • and more!

Your timeline doesn’t have to be one single string, either. This plugin allows for more than one element per spot in your timeline.

The Content Timeline – Responsive WordPress Plugin for Displaying Posts/Categories in a Sliding Timeline is unique, beautifully designed, and the perfect WordPress user interface for presenting in a timeline format.

3. UberChart – WordPress Chart Plugin

If you want to share data visually, you’d be hard-pressed to find a better way to build and present it than UberChart – WordPress Chart Plugin.

It’s highly customizable and ready to drop into your WordPress install.

UberChart - WordPress Chart Plugin

“UberChart is an advanced WordPress Chart Plugin which gives you the ability to create a great variety of charts with exceptional customizability.”

It’s feature set includes:

  • 240 customizable options for each chart
  • embedded spreadsheet editor
  • import and export data
  • fully responsive

And it includes ten different chart types:

  1. Line
  2. Area
  3. Bar
  4. Horizontal Bar
  5. Pie
  6. Doughnut
  7. Radar
  8. Polar Area
  9. Scatter
  10. Bubble

UberChart – WordPress Chart Plugin is impressive.

4. Theia Post Slider for WordPress

Transform your multi-page posts into slides that are easy to use and easy to read.

Theia Post Slider for WordPress works with existing posts and includes 60 different slider themes.

Theia Post Slider for WordPress

“…Theia Post Slider for WordPress transforms your multi-page posts into slideshows, making them much more engaging and easier to browse.”

Supports:

  • uses AJAX with JavaScript fallback
  • vector icons and retina-ready
  • titles, headers, and footers
  • SEO optimized
  • and more

A lot of thought has been put into this WordPress user interface plugin. From SEO to speed and usability to customization, the Theia Post Slider for WordPress really delivers.

5. Progress Map WordPress Plugin

The Progress Map WordPress Plugin is feature rich. I most certainly can’t do it justice with this short summary.

The vision behind this WordPress user interface plugin is this:

“The aim is to help users having websites like hotel listings, real estate listings, restaurant listings, job listings, store listings & more… to list their locations on Google map and to easily navigate through the map using a carousel.”

Progress Map WordPress Plugin

And it delivers:

  • search filter and distance search
  • Custom Post Type support
  • custom markers
  • 70+ map styles
  • geo-targeting
  • retina ready
  • and much, much more

Progress Map WordPress Plugin is easily one of the most robust map plugins you’re going to find.

This plugin is all over the map.

6. Slider Revolution Responsive WordPress Plugin

When you need a slider—especially if you want an easy way to build it—you have to consider the Slider Revolution Responsive WordPress Plugin.

Animations, color pickers, layers—it’s got it all baked in.

Slider Revolution Responsive WordPress Plugin

Slide types include:

  • social media feeds
  • media galleries
  • hero blocks
  • carousels
  • sliders
  • and more

The number one feature that makes this slider appealing is the powerful visual editor. Sliders are sliders, but the Slider Revolution Responsive WordPress Plugin brings a complete, robust slide designer suite.

7. Slick Menu – Responsive WordPress Vertical Menu

Slick. Responsive. Vertical. Menu.

The Slick Menu – Responsive WordPress Vertical Menu is exactly that, with a little extra on the side.

Slick Menu - Responsive WordPress Vertical Menu

“Slick Menu is more than just a menu plugin. It can be used to create unlimited multi level push menus or content sidebars with rich content, multiple style options and animation effects.”

Customize your:

  • background colors
  • custom fonts
  • patterns
  • overlays
  • images
  • videos
  • and more

Each level is independently customizable, making it super easy to build great WordPress user interfaces without expensive design apps or code knowledge. 

Slick Menu – Responsive WordPress Vertical Menu is an awesome option for vertical menus and more!

8. Cool Timeline Pro – WordPress Timeline Plugin

Add a timeline to blog posts, organization history pages, and more with the Cool Timeline Pro – WordPress Timeline Plugin.

Create both horizontal and vertical timelines with its built-in designs and beautiful animation effects.

Cool Timeline Pro - WordPress Timeline Plugin

Features include:

  • convert any Post Type into a timeline
  • pagination for long timelines
  • create multiple timelines
  • add icons
  • and more

Simple, clean, and flexible.

The Cool Timeline Pro – WordPress Timeline Plugin is a great way to build a timeline from your current content or building a new, standalone timeline to help communicate to your reader.

9. LoftLoader Pro – Preloader Plugin for WordPress

Sometimes you need more time for something to load. Videos? Lots of HD images?

Easily add a loading animation to your pages with the LoftLoader Pro – Preloader Plugin for WordPress.

It’s pretty fancy.

LoftLoader Pro - Preloader Plugin for WordPress

Features include:

  • adjust minimum load time
  • 18 CSS3 animations
  • works on all devices
  • built-in editor
  • and more

The LoftLoader Pro – Preloader Plugin for WordPress makes it easy to add an animated loading screen—no coding required.

10. Superfly — Responsive WordPress Menu Plugin

Replace your current WordPress menu or enhance it with the Superfly — Responsive WordPress Menu Plugin.

This plugin is power packed and easy to use.

Superfly  Responsive WordPress Menu Plugin

“Superfly is a responsive WordPress menu plugin that generates space efficient vertical push/sliding/static navigation, icon toolbar or fullscreen menu on your choice.”

Menu design options include:

  • side, skewed, and full screen menus
  • image backgrounds
  • static or anchored
  • iconbar
  • and more

The Superfly — Responsive WordPress Menu Plugin also includes display options, making it super easy to build the right menu for the right user interface.

11. Ultra WordPress Admin Theme

There’s customizing the WordPress Admin. And then there’s the Ultra WordPress Admin Theme.

This WordPress user interface takes Admin customizations to a whole new level.

Ultra WordPress Admin Theme

White label branding is just the start of it:

  • admin menu management
  • create your own theme
  • import/export settings
  • and much, much more

From the login screen to the admin top bar, the Ultra WordPress Admin Theme makes the entire WordPress Admin experience fully customizable.

12. Different Menu in Different Pages

If you need different menus in different pages, you’ll want to use Different Menu in Different Pages.

It also supports bbPress, WPML, WooCommerce, and BuddyPress.

Different Menu in Different Pages

Easily create multiple menus and locations based on:

  • custom taxonomies
  • categories
  • pages
  • posts
  • and tags

It also includes a shortcode option to show your menu within content as well.

The Different Menu in Different Pages is lightweight and proves useful in any WordPress toolbox.

13. Popup Plugin for WordPress – Layered Popups

As much as I hate popups, sometimes you just need a popup. The Popup Plugin for WordPress – Layered Popups is the easiest way to build and display popups on your WordPress site.

Popup Plugin for WordPress - Layered Popups

“[The] internet is full of boring popups. So, it’s a time to break this trend.”

Features included, but certainly not limited to:

  • jQuery and CSS3 animations
  • social network integration
  • A/B campaign stats
  • 200+ popup library
  • mobile friendly
  • and much, much more

Popup types include:

  • OnLoad Popup
  • OnScroll Popup
  • OnClick Popup
  • OnExit Popup
  • OnIdle Popup

And also features:

  • Sidebar Widget
  • Link Locker
  • Inline Form
  • and more

The Popup Plugin for WordPress – Layered Popups is a robust solution that looks great to users and proves useful for admins.

14. The Team Pro – Team Showcase WordPress Plugin

The Team Pro – Team Showcase WordPress Plugin claims to be “the most versatile WordPress plugin available to create and manage your Team page.”

I think they’re right.

The Team Pro - Team Showcase WordPress Plugin

Style options include:

  • slide-ins
  • drawer
  • circles
  • modal
  • table
  • cards
  • grid
  • list

With these 8 presets, over 20 style options, and clean designs, your team never looked so good with The Team Pro – Team Showcase WordPress Plugin.

15. UberMenu – WordPress Mega Menu Plugin

This is a WordPress user interface element that I really like but can be difficult to implement.

But it’s easy with the UberMenu – WordPress Mega Menu Plugin!

UberMenu - WordPress Mega Menu Plugin

Your WordPress menu will never be the same again:

  • enhanced mobile experience
  • easily add images and icons
  • build beautiful menu layouts
  • columns, rows, maps, forms, and more

Tabbed submenus? Google Fonts? Vertical or horizontal? UberMenu – WordPress Mega Menu Plugin has it.

16. Floatton | WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents

This isn’t just another popup. While it does include a popup feature, it includes a number of unique features that get it on this list.

Floatton | WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents has a clean design and is one of those plugins that’s always nice to have in your WordPress toolbox.

Floatton  WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents

“Floatton is a premium WordPress plugin that helps you create sticky Floating Action Button with tooltip-styled popup contents to give your user easily accessible contents throughout your website.”

Use it as a:

  • comment and contact form
  • cookie or legal consent
  • newsletter sign up
  • shopping cart lists
  • announcements
  • rating form
  • video code
  • login

And anything else you can think of!

Add some user interaction. Add Floatton | WordPress Floating Action Button with Pop-up Contents for Forms or any Custom Contents.

17. StickyVideo for WordPress

If you’ve used YouTube on a mobile device, you’ve experienced the great UI/UX feature whereby when you begin to scroll away from the video, it will snap the video into the corner, so you can continue to watch while you scroll through the content.

That’s exactly what StickyVideo for WordPress does, pinning videos to the side when users begin to scroll away.

StickyVideo for WordPress

“Boost viewability rates using a technique employed by CNN, Daily Mail and the Washington Post that pins videos to the side while you scroll!”

This plugin will pin videos hosted by:

  • WordPress (Self hosted in Media Library)
  • YouTube
  • Vimeo
  • Dailymotion
  • Facebook
  • Brightcove
  • JW platform
  • Youku
  • Tudou
  • Wistia
  • SchoolTube
  • Break
  • Metacafe
  • LiveLeak
  • Archive.org

Install, configure, and your videos won’t be scrolled past any longer with the StickyVideo for WordPress plugin.

18. Ultimate Image Hover Effects Plugin For WordPress

Nothing catches a user’s eye more than a tasteful image hover effect. And the Ultimate Image Hover Effects Plugin For WordPress brings hover effects in spades.

Ultimate Image Hover Effects Plugin For WordPress

No matter which WordPress theme you’re running, you’ll enjoy:

  • grid and carousel layouts
  • 40 plus box animations
  • over 200 effects
  • fully responsive
  • and more

The Ultimate Image Hover Effects Plugin For WordPress comes with just enough options to be both easy to use and lightweight.

19. Testimonials Showcase – WordPress Plugin

Display and manage your client, customer, and supporter testimonials easily with the Testimonials Showcase – WordPress Plugin.

Testimonials never looked so good.

Testimonials Showcase - WordPress Plugin

Features include:

  • over 15 layout customization options
  • grid or slider layout
  • star rating system
  • and more

The Testimonials Showcase – WordPress Plugin also includes front-end submissions.

20. WP Logo Showcase Responsive Slider Pro

It’s time to amp up your portfolio page. It’s time for WP Logo Showcase Responsive Slider Pro.

This WordPress plugin is designed to showcase a designer’s work, but it can also be used to display client and partner logos or anything else that fits within this type of user interface.

WP Logo Showcase Responsive Slider Pro

This responsive slider features:

  • includes both a slider and grid widget
  • tooltip and custom animation options
  • over 15 predefined designs
  • drag and drop admin
  • and more

Some sliders try to offer everything, while the WP Logo Showcase Responsive Slider Pro focuses on one particular niche and style of slider and nails it perfectly.

Conclusion

Having a good user interface can often make or break your website. You can have a great layout, great colors, and great content, but if you don’t have a good interface, your users aren’t going to use your website.

These 20 popular WordPress user interface elements from Envato Market are certainly worth a consideration, but if you still didn’t find what would work best, you may want to dig into development with the WordPress Plugin Development Essentials, the WordPress Hacker’s Guide to the Galaxy, or some helpful eBooks like Useful Tricks and Techniques for WordPress or Mastering WordPress.

What are your favorite and most effective WordPress user interface elements?


Source: Nettuts Web Development

Angular vs. React: 7 Key Features Compared

Angular vs React

Angular vs. React is a popular debate among front-end JavaScript developers and, more often than not, the discussion ends up being biased towards one technology or the other. Developed by Google and Facebook respectively, Angular and React are the two popular technologies used to build interactive single-page applications. 

A comprehensive comparison between Angular and React is imminent because there are certain places in which they significantly overlap in terms of what they offer, i.e. building the front-end view of your application and other places where their functionality remains incomplete unless helped by a third-party library. Adopting one technology over the other is a question of whether Angular or React better solves your problem and a bit of intuition. In this tutorial, we’ll compare and contrast seven key different features of Angular and React.

I am an ardent proponent of the code-first approach (code speaks louder than words, they say). Keeping this in mind, I’ve added code samples of Angular and React wherever possible so that you can build on your intuition and decide which works for you and which doesn’t.  Let’s get started.

Framework vs. Library

Angular is a framework, while React is a library. 

So what does this mean? React on its own won’t let you create a web application because it is designed to create views (hence the ‘V’ in MVC). What React can do is build component-based views for which data can be passed down to child views. To fill this void, Facebook has developed Flux, which is an architectural pattern that complements React. Flux architecture, when coupled with React, provides the following scenario:

  1. The user clicks on a React element. 
  2. An action is fired. This action is dispatched to a Store via a Dispatcher library.
  3. The Store keeps track of the application’s state and data retrieval methods. Any update to the state is reflected in the views, and this helps to keep the views consistent with the state of the application.

Doesn’t make sense? This figure should sort it out for you.

An image that depicts how the Flux architecture complements React
Flux complements React and implements the concept of Unidirectional data flow.

Angular is a framework for building client applications.

AngularJS was firmly built on top of the MVC pattern, which separated the application into three different layers. The combination of model, view, and controller plus the added complexity involved in mastering directives, factories, services and other components to create a single-page application forced the developers at Google to shift towards a component-based architecture. 

But when your application starts to grow, it’s important to have a solid structure that keeps the business logic of your application away from the components. Being a framework, Angular allows you to enforce structural organization by moving the business rules into a domain model (using a combination of model classes and services) and injecting the model into your components via dependency injection.

Here is a sample of code that illustrates how the business logic is encapsulated inside a User model and a User service, and away from our component.

Component-Based Approach

Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components.

What are components? In Angular, components are TypeScript classes that have a @Component decorator marked over them. Moreover, inside these decorators, we can define what Angular calls the meta-data, which includes the template, styles, selectors and so forth.  

Component hierarchy in Angular is designed in such a way that you can associate structure and functionality under a single entity. Here is a high-level architectural overview of components and how this links to everything else in Angular. 

The architecture of Angular
The architecture of Angular. Component at the center, and everything else revolves around it. 

Data sharing among components is possible by nesting components, as exemplified below.

The concept of components is deeply rooted in React, just as it is in Angular. Facebook calls React a component-based library that lets you build interactive user interfaces. However, unlike Angular, React components are just JavaScript functions with an arbitrary number of inputs and an output. The code below shows a component defined using a JavaScript function and using an ES6 class.

We will be adhering to the ES6 standards for composing components henceforth because that is what Facebook recommends. Each React component accepts an arbitrary number of inputs, which is stored inside an object named props

It also has a render method, and as the name suggests, this method determines what will be rendered when the component is invoked. Each component maintains an internal state (via this.state), and every time the state changes, the render function of that component is invoked again.

Language Features: TypeScript vs. ES6

Angular applications are written in TypeScript, which is a superset of ECMA2015 and uses a transpiler to compile your strongly typed .ts file to a plain .js file. TypeScript offers language extensions that are designed to make writing in JavaScript easier, and it associates type information with JavaScript entities to enforce type checking and enhance the development workflow.

Some of the key features of TypeScript include optional static typing and support for interfaces, classes, and decorators. (Decorators are functions that are prefixed with ‘@’ and immediately followed by a class, parameter, or a property.)

Let’s dive into React, shall we? One of the important language features in React is evident in this code sample. 

Isn’t this great? React lets you embed XML/HTML tags into your JavaScript file, and this is done through JSX, which offers syntax extension capability to JavaScript. We have to use a compiler like Babel, which compiles our JSX code into the JavaScript that browsers can understand. The above code compiles down to this:  

Although using JSX is recommended, you can stick with React.createElement() if you are against the idea of embedding HTML tags into JavaScript.

Furthermore, you can use either ES6 standards or the traditional form of JavaScript while working with React. Although ES6 is relatively new, it adds a lot of features such as classes, arrow functions, template literals, destructing, and the use of let and const. The only downside I can think of is that it adds a little bit of boilerplate code such as the need to call super() every time you call a constructor(), and that it doesn’t automatically bind event-handling methods with this.

Type Checking in Angular vs. PropTypes in React

Static type checking is performed at compile time. The compiler warns you about potential type mismatches and detects certain errors that would otherwise go unnoticed. Additionally, defining a contract on a variable, a property, or the parameters of a function can result in more readable and maintainable code.

Variable and function declarations are made more expressive by declaring their data types. You can read more about the different primitive data types in the TypeScript documentation.

Defining the signature of an API using an interface makes the code less ambiguous and easier to comprehend. The interface serves as a quick start guide that helps you get started with code immediately and saves time otherwise spent on reading the documentation or the actual implementation of the library.  

The type keyword in TypeScript can be used to create an alias for a type. You can then create new types which are a union or intersection of these primitive types.

React has limited support for type checking because the underlying ES6 doesn’t support it. Nevertheless, you can implement type checking using the prop-types library developed by the React team. Type checking the props of a component to check whether it is a string can be done as shown below.

But prop-types are not limited to strings, numbers, and boolean. You can do a lot more, as described in the prop-types library documentation. However, if you take static type checking seriously, you should use something like Flow, which is a static type-checker library for JavaScript.

Scaffolding: Angular CLI vs. create-react-app

Starting a project from the ground up might seem fun initially. However, the process of setting up the directory structure, writing boilerplate code for components, and getting the application bootstrapped is a futile and unproductive exercise. Your strategy should be to get on with it as quickly as possible and focus on the actual development of the application. Thanks to Google and Facebook, you have tools available to create and scaffold your applications with ease.

Setting up Angular-CLI for angular and create-react-app for React is straightforward using npm.

To create a new Angular application, you should use the following command:

But that’s not it. The ng generate command lets you generate components, routes, pipes, directives, and services.

Angular CLI can do a lot more, like creating a build of your Angular app, commands for running unit tests, and end-to-end testing. You can read more about it on GitHub.

On the other hand, create-react-app is the officially supported way of creating a React app without any configuration files.

$ npm install -g create-react-app

This should create a functional React app with all the Babel and webpack dependencies taken care of. You can start running the app on your browser using npm start.

You can find the scripts available for the react app in the package.json file.

Data Binding: Two-Way Binding vs. Unidirectional Binding

Data binding is a feature that enables synchronization of data between the application state (model) and the view. In a one-way data binding routine, any change in the state of the application automagically updates the view. On the contrary, two-way data binding binds together properties and events under a single entity, i.e. any modification of the model updates the view and vice versa.  

In React, the properties are passed down from parent to child components, which is known as the unidirectional or top-down data flow. The state of a component is encapsulated and is not accessible to other components unless it is passed down to a child component as a prop, i.e. the state of a component becomes the prop of the child component. 

But what if you need to propagate the data up through the component tree? This is done through child events and parent callbacks. The React documentation includes a good example that deals with such a scenario.

Data binding techniques available in Angular are among a few features that make it interesting. Angular has out-of-the-box support for interpolation, one-way binding, two-way binding, and event binding.

Interpolation is the simplest way to bind your component property inside the text between your HTML tags and attribute assignments.  

<p>Welcome back {{currentUser.name}}!</p>

Property binding is similar to interpolation in the sense that you can bind the properties of your view elements to component properties. Property binding favors component communication and is identical to how props are passed down in React.

<img [src]="userImgUrl">

<user-child [user]="currentUser"></user-child>

Event bindings allow data flow in the opposite direction, i.e. from an element to a component. Here, click is a target event, and on the right, we have the onSave() method that gets invoked when the event occurs.  

<button (click)="onSave()">Save</button>

But the most important feature is the two-way binding using the [(ngModel)]. This merges the property binding and event binding under one directive and is particularly useful with forms and input fields. 

Server-Side Rendering

Server-side rendering is a traditional rendering technique. Here, the server returns the whole HTML file upon request, and the browser is left with the simple job of displaying it to the user. Client-side rendering, on the other hand, returns a bare-bones HTML document, the stylesheet, and a JavaScript file. 

The JavaScript makes subsequent requests to render the rest of the website using a browser. React, Angular and all other modern JavaScript front-end libraries are good examples of client-side rendering. This is evident if you view the source of your Angular/React application.

But client-side rendering has the drawbacks that it doesn’t work great for SEO and that it returns incomplete HTML content when you share your link on social media sites. Angular has a solution called Angular Universal that takes care of making your app search engine friendly and social media friendly. It’s a library built by the Angular team, and using it is definitely favored. 

Universal makes use of a pre-rendering technique where the whole website is rendered from the server first, and after a couple of seconds, the user is switched to the client-side rendering. Since all this happens under the hood, the user doesn’t notice anything different.

If you are using React with Redux, the Redux documentation has a good tutorial on setting up server rendering. You can also set up React to render from the server using the BrowserRouter and StaticRouter components available in the react-router library. You can read more about it in this Medium article. But if you are into performance and optimization, you can try next.js, which is a library for SSR in React.

Wrapping It Up

Comparing a full-blown, feature-rich framework to a robust UI library might not seem fair. However, they are advanced JavaScript technologies used to create interactive single-page applications, and in that regard, this article should help you decide on choosing one of them. 

What are your thoughts on Angular vs. React? Do share them in the comments below.


Source: Nettuts Web Development

10 Elegant CSS Pricing Tables for Your Latest Web Project

Pricing tables are an important tool for businesses promoting and selling their products or services on their website. As such they need to be simple
and attractive in design, to highlight the most important information
about each product or service and to clearly differentiate between available
features, options and costs so that potential customers find it easy and
intuitive to choose the most
appropriate plan for their needs.

Here we’ve compiled a list of the 10 most tastefully
designed CSS pricing tables to be found at CodeCanyon. Some are quite minimalist in
their design, others provide a dizzying range of options, and others still take
a somewhat more creative approach to design and function. No matter what you’re
looking for, you’re bound to find a pricing table here that will suit your
needs.

1. Comparative
Responsive Pricing Tables

Comparative Responsive Pricing Tables offers a wide array of
options for designing your pricing tables. Users can select any of 13 unique
designs which they can then customise in variety of ways with a selection of
hover animations, colour schemes, tooltips, etc. These tables, which are fully
responsive, use Font Awesome icons and are also cross-browser compatible.

Customers reviewing this product have described it as a “very
good product that comes with premium service.”

Comparative Responsive Pricing Tables

Best features:

  • 13 unique designs
  • tooltips with text and lists
  • multiple colour themes for each design
  • three types of hover animation
  • and much more

Comparative
Responsive Pricing Tables
is exactly what you need if you’re looking for feature-rich
design options for creating your pricing tables.

2. CSS3
Responsive WordPress Compare Pricing Tables

CSS3 Responsive WordPress Compare Pricing Tables is a
CodeCanyon bestseller and for good reason. Like Comparative Responsive Pricing
Tables above, it offers a wide range of highly customisable design options from
simple static tables to tables with sliding columns, crossfade animation
columns, various hover features and tables with images. It also offers browsers
support for the six most popular browsers on the market.

Customers like these pricing tables because they say they’re
very flexible and “well designed for any kind of comparison with multiple
adjustment options.”

CSS3 Responsive WordPress Compare Pricing Tables

Best features:

  • admin panel with live configuration
  • 20 predefined colour versions
  • unlimited number of columns and rows
  • ability to set different width values and font sizes for each
    column
  • and much more

A solid performer CSS3
Responsive WordPress Compare Pricing Tables
will hold its place in the
pricing tables market for years to come.

3. Responsive
Multi Style Bootstrap Pricing Tables

Responsive Multi Style Bootstrap Pricing Tables is another
good choice for users looking for pricing tables that offer a wide range of
design possibilities.

Responsive Multi Style Bootstrap Pricing Tables comes with three different attractive designs, and each design can be configured in several different ways
using 20 different colour schemes. Users can decide whether they want to use
the pricing tables with or without Bootstrap.

Responsive Multi Style Bootstrap Pricing Tables

Best features:

  • three different designs
  • 20 colour themes for each design
  • hover effects
  • tooltips
  • Font Awesome icons
  • and much more

Responsive
Multi Style Bootstrap Pricing Tables
is not a WordPress plugin; however, WordPress
users can purchase a WordPress version.

4. Pure
CSS Responsive Pricing Tables for WordPress

Pure CSS Responsive Pricing Table for WordPress is a
Bootstrap integrated plugin for WordPress that provides users with 15
predefined themes which are easy to use, highly customisable, and provide unlimited
colours and styles to fit into your existing WordPress theme.

Support for the plugin is provided via email and includes answering
technical questions about the item’s features and assistance with reported bugs
and issues.

The Pure CSS Responsive Pricing Table for WordPress

Best features:

  • create unlimited tables
  • drag and drop column and row sorting
  • PayPal integrated
  • Google Fonts supported
  • and much more

Around since 2015, Pure
CSS Responsive Pricing Tables for WordPress
has
been consistently updated to keep it a crowd favourite.

5. Pricing—Responsive
CSS3 Pricing Table

Pricing—Responsive CSS3 Pricing Table is the latest pricing
table plugin to arrive on CodeCanyon. It’s fully responsive, build on the
Bootstrap framework and compatible with Firefox, Safari, Opera, Chrome, Edge, and
IE10 and IE11 browsers.

These pricing tables are fully customisable but do not offer
a wide variety of styling choices, so will appeal to users looking to create
tables with simple and clean, yet attractive design.

Responsive CSS3 Pricing Table

Best features:

  • responsive and mobile-friendly layout
  • month/year pricing toggle included
  • button CSS3 effect, hover CSS3 effect
  • and much more

With its stripped-back design, Pricing—Responsive
CSS3 Pricing Table
is definitely the newcomer to watch.

6. Great
Pricing Tables Framework

Another newcomer to CodeCanyon, Great Pricing Tables
Framework’s strength is its simplicity and ease of use.

The plug features a responsive design and three style variations.
Like the other plugins featured here, it uses standard HTML5 and CSS3
technology and has wide cross-browser compatibility.

Great Pricing Tables Framework

Best features:

  • easy
    to use
  • responsive design
  • Font Awesome included
  • Bootstrap supported
  • and much more

Great
Pricing Tables Framework
may not offer a
lot of features, but its very clean and simple approach to pricing table design
is definitely its strength.

7. 7
Responsive Flat Bootstrap Pricing Tables

7 Responsive Flat Bootstrap Pricing Tables provides users
with seven distinctly different pricing tables in a minimalist style.

These tables support Bootstrap, with a promised Bootstrap 4
update coming later this year as well as free CSS and jQuery updates in the
future. Customers praise the pricing table’s  “sleek and modern design” that you “can copy and paste
straight onto my site”.

7 Responsive Flat Bootstrap Pricing Tables

Best features:

  • minimalist
    design
  • responsive
  • horizontal
    and well as vertical tables
  • and
    much more

If clean and classic is what you’re looking for, then 7
Responsive Flat Bootstrap Pricing Tables
is the right choice for you.

8. Round
Pricing Tables

Round
Pricing Tables is quite a unique offering among this list of pricing
tables as it offers round pricing tables instead of rectangular ones.

Comparative
prices are displayed in each circle and when visitors move their mouse over each
circle, the list of features offered is displayed. Customers who’ve bought this pricing table
found that it is an excellent product with “good code” that “doesn’t conflict with
others, and is easy to edit.”

Round Pricing Table

Best features:

  • creative design
  • CSS3 animations
  • Google and Font Awesome supported
  • cross browser support
  • and much more

Round
Pricing Tables
obviously
won’t appeal to every user, but for those users with less information to display
and who are looking for a more creative approach to pricing tables, this
pricing table is ideal.

9. Hexagon CSS Pricing Table

The Hexagon CSS
Pricing Table is another pricing table that uses a cool and clever design to bring
a bit of pizazz to your site.

Like Round
Pricing Tables, this pricing table challenges the
tradition pricing tables model, in this case by using hexagons instead of rectangles. Comparative prices are displayed in each hexagon, and when visitors hover over each hexagon, details of each pricing plan
are revealed through any number of different animation effects.

 Hexagon CSS Pricing Table

Best features 

  • 16 different hover styles
  • 12 different colour schemes
  • cool animation effects
  • Google Font and Font Awesome supported 
  • and much more

As is the case with the Round Pricing Table Features, Hexagon
CSS Pricing Table
 will appeal to users who are open to a more creative approach to pricing tables.

10. CSS Pricing Tables

CSS Pricing Tables has been trending recently on
CodeCanyon, probably because users are drawn to its uncomplicated
design. The plugin uses one design but allows users to customise the colours schemes used to create the right look for their site.

CSS Pricing Tables

Best features:

  • responsive design
  • hover effect
  • 361 icons included
  • easy to use
  • and much more

CSS Pricing Tables may not offer enough styling options for many users, but for those looking to get pricing tables up and ready to go in the shortest possible time, these tables are a great choice. 

Conclusion

These 10 elegant CSS pricing tables for your latest web project are by no means the only ones available at Envato
Market
. So if you haven’t found anything here that meets your needs,
we have plenty of other great options on offer.

And if you want to improve your CSS skills, check out our
ever so useful free CSS
tutorials
.


Source: Nettuts Web Development

Getting Started With the Flux Architecture in React

Final product image
What You’ll Be Creating

In this tutorial, you will learn about Facebook’s Flux architecture and how it’s used to handle the data flow in React-based applications. We’ll begin by covering the basics of Flux and understanding the motivation behind its development, and then we’ll practice what we’ve learned by building a simple virtual wallet application.

Throughout the tutorial, I will assume you’ve used React before, but have no experience with Flux. You might get something out of it if you already know the basics of Flux and are looking to gain a deeper understanding.

If you are completely new to the React scene, I recommend going through the Getting Started With React course by David East, here on Envato Tuts+. It’s a fantastic course that will get you up to speed in no time.

What Is Flux?

Flux is mainly an application architecture concept developed by Facebook, but the same term also refers to a library that represents the official implementation.

Facebook came out with Flux as an attempt to solve the problems caused by the MVC pattern in their massive codebase. They struggled with issues where actions triggered cascading updates that led to unpredictable results and code that was hard to debug. This may sound familiar if you’ve used MVC frameworks before, as in most of them everything tends to be tightly coupled. Add watchers and two-way data binding to the mix, and you’ve got yourself a proper headache.

My advice is to avoid any attempt at finding common ground between Flux and MVC. It won’t help much, other than amping up your confusion. Flux attempts to solve things differently, and trying to compare it with other patterns won’t help.

Project Setup

If you’d like to follow along with the tutorial, first make sure you have the required software installed. When you have finished, clone the boilerplate branch from the GitHub repository I prepared to accompany this article.

Here are the software requirements and the versions I had installed at the time of writing this article:

  • Git: 2.11
  • Node.js: 6.9
  • NPM: 3.10
  • Yarn: 0.22
  • Your editor of choice

The boilerplate serves as a starting point for the upcoming small project that we will be building, a small virtual wallet app. It contains the Webpack configuration for transpiling the ES6 syntax to plain JavaScript and WDS for serving the files. It also has some CSS component styles so you can jump right into coding.

In order to install all the required dependencies, cd into the project directory and run yarn.

In the next section, you will be setting up the application’s core components before integrating Flux. I haven’t included them in the boilerplate as I believe it would create more confusion. If you’re not interested in building the app, you can skip these steps and jump to the next section.

Components Setup

Start by including the following code inside js/index.js, which serves as the application’s entry point:

For the main <App /> component, create a new file inside js/components called App.js and add the following code:

The <App /> component wraps two other components, one for the form responsible for adding new items and another one for the list of items. To create the <AddNewItem /> component, create a new file AddNewItem.js inside js/components and add this code:

The component bundles some logic for updating the state when the form fields update and also some basic validation. Let’s finish off the components setup by creating the last one inside js/components/ItemsList.js for the items list, using this code:

That’s it! You’re done setting up the project’s components. The great part is that they also come with free styling.

Run yarn start and wait for the bundle to build. If you point your browser to localhost:8080, you should see the app without any functionality.

Next, we’ll cover what Flux is and how you can use it to add functionality to the virtual wallet application.

The Flux Building Blocks

At a high level, Flux breaks down into four major parts: actions, the dispatcher, stores, and views:

  • Actions describe an action that took place in the application.
  • The dispatcher is a singleton registry of callbacks. It acts as a middleman by passing the actions to all the stores that subscribed to it.
  • Stores manage the state and logic needed to update it for specific parts of the application.
  • Views are plain old React components.

In Flux, all data flows in a single direction:

  • Actions are passed to the dispatcher using convenience classes called action creators.
  • The dispatcher sends (is dispatching) the actions to all the stores that subscribed to it.
  • Finally, if the stores care about a particular action that was received (or more), they update their state and signal the views so they can re-render.

Below is a visual representation of this process.

Representation of how data flows in a Flux application

Actions

Data is sent “through the wire” in a single direction using plain JavaScript objects called actions. Their job is to describe an event that took place in the application and to transport the new data to the stores. Each action must have a type and an optional payload key that contains the data. An action looks similar to the one below:

The action’s type must be represented by a descriptive and consistent uppercase string—similar to the common convention of defining constants. They serve as unique IDs that stores will use to identify the action and respond accordingly.

A common practice is to define all action types in a constants object and reference that object instead across the application to maintain consistency. Our virtual wallet will support a single action, which adds items to the list—both expenses and financial gains will be treated as a single item—so our constants file will be very slim.

Create an index.js file in the js/constants folder and use the following code to create your first action type:

Actions are passed to the dispatcher using convenience class helpers called action creators that handle the simple task of creating and sending the action to the dispatcher. Before creating our action creator, let’s see what the dispatcher does first and understand its role in Flux.

The Dispatcher

The dispatcher is used to coordinate the communication between action creators and stores. You can use it to register a store’s actions handler callback and also to dispatch actions to the stores that subscribed.

The dispatcher’s API is simple, and it has only five methods available:

  • register(): Registers a store’s action handler callback.
  • unregister() : Unregisters a store’s callback.
  • waitFor(): Waits for the specified callback(s) to run first.
  • dispatch(): Dispatches an action.
  • isDispatching(): Checks if the dispatcher is currently dispatching an action.

The most important are register() and dispatch() as they’re used to handle most of the core functionality. Let’s see how they look and work behind the scenes.

This is, of course, the basic gist. The register() method stores all callbacks in a private _callbacks array and dispatch() iterates and calls each callback stored using the received action.

For simplicity, we won’t write our own dispatcher. Instead, we’ll use the one provided in Facebook’s library. I encourage you to check out Facebook’s GitHub repo and see how it’s implemented.

Inside the js/dispatcher folder, create a new file index.js and add this code snippet:

It imports the dispatcher from the flux library—which was installed using yarn earlier—and then exports a new instance of it.

Having the dispatcher ready now, we can get back to actions and set up our app’s action creator. Inside the js/actions folder, create a new file called walletActions.js and add the following code:

The WalletActions class is exposing an addNewItem() method that handles three basic tasks:

  • It receives an item as an argument.
  • It uses the dispatcher to dispatch an action with the ADD_NEW_ITEM action type we created earlier.
  • It then sends the received item as payload along with the action type.

Before putting this action creator to use, let’s see what stores are and how they fit in our Flux-powered application.

Stores

I know, I said you shouldn’t compare Flux with other patterns, but Flux stores are in a way similar to models in MVC. Their role is to handle the logic and store the state for a particular top-level component in your application.

All Flux stores must define an action handler method that will then be registered with the dispatcher. This callback function mainly consists of a switch statement on the received action type. If a specific action type is met, it acts accordingly and updates the local state. Finally, the store broadcasts an event to signal the views about the updated state so they can update accordingly.

In order to broadcast events, stores need to extend an event emitter’s logic. There are various event emitter libraries available, but the most common solution is to use Node’s event emitter. For a simple app like a virtual wallet, there’s no need for more than one store.

Inside the js/stores folder, create a new file called walletStore.js and add the following code for our app’s store:

We start by importing the required dependencies needed for the store, beginning with Node’s event emitter, the dispatcher followed by the ActionTypes. You will notice that below it, there is a constant CHANGE, similar to the action types you learned about earlier. 

It’s actually not one, and it shouldn’t be confused. It’s a constant used for the event trigger when the store’s data change. We will keep it in this file as it isn’t a value used in other parts of the application.

When initialized, the WalletStore class starts by registering the _registerToAction() callback with the dispatcher. Behind the scenes, this callback will be added to the dispatcher’s _callbacks array. 

The method has a single switch statement over the action’s type received from the dispatcher when an action is dispatched. If it meets the ADD_NEW_ITEM action type, it then runs the _addNewItem() method and passes along the payload it received.

The _addNewItem() function sets an id for the item, pushes it to the list of existing items, and then emits a CHANGE event. Next, the getAllItems() and getTotalBudget() methods are basic getters, which we’ll use to retrieve the current store’s state and the total budget.

The final two methods, addChangeListener() and removeChangeListener(), will be used to link the React components to the WalletStore so they get notified when the store’s data change.

Controller Views

Using React allows us to break down parts of the application into various components. We can nest them and build interesting hierarchies that form working elements in our page.

In Flux, components located at the top of the chain tend to store most of the logic needed to generate actions and receive new data; therefore, they are called controller views. These views are directly hooked into stores and are listening for the change events triggered when the stores are updated.

When this happens, controller views call the setState method, which triggers the render() method to run and update the view and send data to child components through props. From there, React and the Virtual DOM do their magic and update the DOM as efficiently as possible.

Our app is simple enough and does not respect this rule by the book. However, depending on complexity, larger apps can sometimes require multiple controller views with nested sub-components for the major parts of the application.

Fitting It Together

We’ve finished covering the major parts of Flux, but the virtual wallet app is not yet completed. In this last section, we’ll review the entire flow from actions to views and fill in the missing code needed to complete Flux’s unidirectional data flow.

Dispatching an Action

Getting back to the <AddNewItem /> component, you can now include the WalletActions module and use it to generate a new action in the _addNewItem() method.

Now, when the form is submitted, an action is dispatched and all stores—one in our case—are notified about the new data.

Listening for Store Changes

In your WalletStore, currently when an item is added to the list its state changes and the CHANGE event is triggered, yet no one is listening. Let’s close the loop by adding a change listener inside the <ItemsList /> component.

The updated component closes Flux’s unidirectional data flow. Note that I skipped including the entire render() method to save some space. Let’s go step by step through what’s new:

  • The WalletStore module is included at the top.
  • The initial state is updated to use the store’s state instead.
  • A new _onChange() method is used to update the state with the new data from the store.
  • Using React’s lifecycle hooks, the _onChange() callback is added and removed as the store’s change listener callback.

Conclusion

Congrats! You’ve finished building a working virtual wallet app powered by Flux. You’ve learned how all the Flux components interact with each other and how you can add structure to React apps using it.

When you’re feeling confident in your Flux skills, make sure you also check out other Flux implementations like Alt, Delorean, Flummox or Fluxxor and see which one feels right for you.

Let me know your thoughts in the comments below, I’d love to know what you think about Flux or assist if you’re having difficulties following the tutorial. If you’d like, you can also reach me on Twitter @hiskio.


Source: Nettuts Web Development

Getting Started With Matter.js: The Composites and Composite Modules

In the third tutorial of the series, you learned about different methods and properties of the Body module in Matter.js. The Body module enables you to manipulate simple bodies like circles, rectangles, and trapeziums. Matter.js also has other modules to help you create and manipulate some complex but common composite bodies like cars, chains, pyramids, stacks, and soft bodies. 

All these composites and the methods to manipulate them are available in the Composite and Composites modules in Matter.js. In this tutorial, you will begin by learning about different composites like pyramids and cars etc. that can be created using the Composites module. After that, we will go over some important methods and properties available in the Composite module.

Creating a Stack and a Pyramid

A stack and a pyramid are both very similar to each other. A stack can be created by using the stack(xx, yy, columns, rows, columnGap, rowGap, callback) function. Similarly, you can create a pyramid with the help of the pyramid(xx, yy, columns, rows, columnGap, rowGap, callback) function. As you can see, all the parameters are the same in both cases. In fact, the pyramid formation is derived from the stack formation. 

The names of all the parameters are self-explanatory. The xx and yy parameters used in this function are used to specify the starting point of the composite. The columns and rows parameters determine the number of columns and rows in the composite. The gap between different rows and columns can be controlled using the columnGap and rowGap parameters. 

Under the influence of gravity, the rowGap generally vanishes in most cases without changing the composite. However, sometimes the resulting momentum of individual bodies can move the bodies under them. This can change the shape of the composite.

The callback function is used to create bodies that can be arranged in either a grid arrangement or a pyramid arrangement based on the function used. This means that you can use it to create a stack or pyramid of rectangular boxes or trapezoids. You should keep in mind that using a circle will make the arrangements unstable. Here is the code to create a stack of rectangles:

You can make the callback function as complex as you wish. In this case, I have used the render options that we learned about in the Body module tutorial to create only orange rectangles with black outlines.

Here is some very similar code to create pyramid shapes in Matter.js:

When you start creating a lot of pyramids with different parameters, you will notice that the number of rows created is sometimes less than the number of rows you specified. This is because the library uses the following formula to calculate the number of rows:

You can carefully place a stack or another pyramid over a pyramid to create interesting patterns. For example, you could place a smaller pyramid over the red one to create a complete pyramid with two colors.

Creating a Car and a Chain

A car in Matter.js is a structure consisting of two wheels and a body. The wheels are created with a friction of 0.8 and density equal to 0.01. You can create a car using the function car(xx, yy, width, height, wheelSize). The xx and yy parameters are used to specify the position of the car. 

The width and height determine the dimensions of the main body of the car. The wheelSize parameter is used to specify the radius of the wheels. There is no need for a callback function as the type of bodies needed to create a car is predetermined.

You can use the chain(composite, xOffsetA, yOffsetA, xOffsetB, yOffsetB, options) function in Matter.js to chain all the bodies in a given composite together using constraints. The offset parameters in the function are used to determine the relative position of the constraints connecting different boxes. 

You will also need additional constraints to hang the chain from a point in the world. Here is the code to create a chain and hang it to the ceiling of our world. 

The boxes in our chain have been created using the stack() function that you learned about earlier. The constraints created by the chain() function have a stiffness of 1. 

This prevents the length of rope between different boxes from changing at all. The additional constraint that we have created here keeps our boxes hanging from the ceiling. 

Here is a demo with a car and the chain created from the above code. You can move the car forward and backward using the orange buttons. Each click applies a force at the center of the first wheel, moving the whole car.

Creating a Soft Body and Newton’s Cradle

A soft body is similar to a stack, with two major differences. The individual elements of the soft body are held together by constraints, and a soft body can only have circles as its constituent elements. You can consider a soft body to be a cross between a mesh and a stack. Creating a soft body is as simple as calling softBody(xx, yy, columns, rows, colGap, rowGap, crossBrace, pRadius, pOptions, cOptions) with the appropriate parameter values. 

You are already familiar with the first six parameters of the function. The crossBrace parameter is a Boolean value that determines if the cross braces should be rendered or not. The pRadius parameter determines the radius of circles, and the pOptions parameter can be used to control other properties of the particles, like mass and inertia. 

The cOptions parameter specifies various options for the constraints that bind the particles together. The following code will create a soft body for our Matter.js world.

Creating a Newton’s cradle is also very straightforward using the built-in newtonsCradle(xx, yy, number, size, length) function. The number parameter determines the number of balls in the cradle. The size parameter determines their radius, and the length parameter determines the length of the rope to which the balls are attached. The library sets the restitution and friction values to zero so that they can continue their motion for a long time.

The following code creates the cradle and moves the first ball to a higher position so that it has some velocity when it falls down and strikes other balls. The position specified by the translate() function is relative to the current position of the body. All these functions and properties of the Body module have been discussed in more detail in the previous tutorial of the series.

Important Methods and Properties in Composite Module

Now that you have learned how to create different kinds of composite bodies, it is time for you to learn about different methods and properties available in the Composite module to manipulate these composites. You can use rotate(composite, rotation, point, [recursive=true]), scale(composite, scaleX, scaleY, point, [recursive=true]) and translate(composite, translation, [recursive=true]) to rotate, scale and translate any composite. These functions are very similar to their Body module counterparts.

You can also add or remove one or more body(s), constraint(s) and composite(s) from a given composite using the add(composite, object) and remove(composite, object, [deep=false]) functions respectively. If you want to move some bodies from one composite to another, you can do so with the help of the move(compositeA, objects, compositeB) function. This function will move the given objects from composite A to composite B.

If you ever want to access all the bodies, composites and constraints that are direct children of the given composite, you can use the composite.bodies, composite.composites and composite.constraints properties to get access to all of them in the form of an array. 

We have already seen how to use the bodies property to translate a ball from the Newton’s cradle to the left and apply a force on the wheel of our car composite. Once you have a reference to individual bodies from the composite, you can use all the methods and properties of the Body module to manipulate them.

Final Thoughts

In this tutorial, you learned how to create some complex composites using the Composite and Composites modules in Matter.js. You also learned about different methods and properties that you can use to manipulate these composites. 

This series was aimed at getting people started with the Matter.js library in a beginner-friendly way. Keeping that in mind, we have covered important functions and properties of the most common modules in the library. 

Matter.js also has a lot of other modules, which we briefly discussed in the first tutorial of the series. If you want to use this library to its full potential, you should read the documentation of all these modules on the official website.

If you have used Matter.js in any of your projects, please tell us about your experience in the comments.


Source: Nettuts Web Development