Must-have JavaScript Framework/Libraries in Your Skillset

JavaScript has come a long way and evolved over the years. There was a time when developers were frustrated with JavaScript issues on the client side and had nightmares to fix cross-browser compatibility issues. The biggest roadblock was the developers had nowhere else to go, other than JavaScript. When the things were looking darkest, jQuery was born. The onset of jQuery was a relief for developers and it made client-side coding an easy ride. jQuery addressed all the JavaScript cross-browser compatibility issues and helped developers to achieve that with fewer lines of code. jQuery is a great library to ease interactions with the DOM, simplified AJAX requests, and made validation easy to implement.

It’s not easy to stay on the top all the time. When the jQuery library was at its peak, it was time for some powerful JavaScript frameworks (Angular, Ember) and other JavaScript libraries (like React) to make front-end coding painless. These libraries and frameworks offer a different way of front-end development and provide great features to make the front-end more powerful and interactive. Now it’s time when almost every month a new JavaScript framework is being introduced and existing frameworks are being updated often. Every framework and library offers unique features, and it’s important for front-end developers to learn them. But it’s impossible to learn and remember everything! Hence, this post talks about some of the most powerful and popular JavaScript frameworks and libraries you must have in your skill set.

Angular


https://angular.io/

Angular is the most popular JavaScript framework available today for building web applications. Angular (commonly referred to as "Angular 2+" or "Angular 2") is a TypeScript-based open-source front-end web application platform led by the Angular Team at Google and by community developers. The initial version of AngularJS (commonly referred to as "Angular.js" or "AngularJS 1.X") is a JavaScript-based web application framework.  AngularJS supports two-way data binding, implements MVC models, dependency injections, use of custom directives, and many more functionalities. Because of some flaws and difficulty in learning Angular 1.x, Angular 2 was created.

Angular 2 was written in TypeScript, a superset of JavaScript that implements many new ES2016+ features. Angular 2 is easier to learn compared to Angular 1.x as it simply focuses on building JavaScript classes. Views and controllers are replaced with components which are easy to read and develop. Angular 2 is modular, mobile-ready, has improved dependency injection, improved data binding, provides better performance and provides more choice for languages to write Angular 2 code.


ReactJS


https://facebook.github.io/react/

ReactJS is the fastest growing JavaScript framework. React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It is an open-source JavaScript library used for building user interfaces specifically for single page applications. It’s used for handling view layer for the web and mobile apps. React also allows us to create reusable UI components.

React allows developers to create large web applications to refresh data on the view without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in the applications. This corresponds to view in the MVC template. It can be used with a combination of other JavaScript libraries or frameworks, such as Angular JS in MVC.

React was first created by Jordan Walke, a software engineer working for Facebook. React first deployed on Facebook’s newsfeed in 2011 and on Instagram.com in 2012. It is maintained by Facebook, Instagram and a community of individual developers and corporations. React is currently being used by many big companies like Netflix, Buffer, Feedly, Airbnb, Walmart, and others.

TypeScript


https://www.typescriptlang.org/

TypeScript is a free and open-source programming language developed and maintained by Microsoft. TypeScript is a superset of JavaScript, which primarily provides optional static typing, classes, interfaces, and aligns with ECMAScript 6 standard proposals. It is compiled in plain JavaScript and does not require any kind of runtime library to support it. It can be used with IDEs such as Visual Studio that allow spotting compile time errors as you type the code. Static checking, symbol-based navigation, and code validations are a few reasons that make TypeScript popular among developers. Angular 2 is completely written in TypeScript. Typescript is an object-oriented way to write JavaScript and therefore it’s easier for object-oriented programmers to adopt.


NodeJS


https://nodejs.org/en/

JavaScript is primarily used for client-side scripting, whereas JavaScript is embedded in a webpage's HTML to be run client-side by a JavaScript engine in the user's web browser. Node.js enables JavaScript to be used for server-side scripting, and runs scripts server-side to produce dynamic web page content before the page is sent to the user's web browser. Node.js is a platform built on Chrome's V8 JavaScript engine for building fast and scalable network applications.

It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. You can write Node.js applications in JavaScript, and can run using the Node.js runtime on OS X, Microsoft Windows, and Linux. Node.js also provides a rich library of various JavaScript modules to simplify the web application development to a great extent.

Ember.js


https://www.emberjs.com/

Ember.js is an open-source JavaScript web framework, based on the Model–view–view-model (MVVM) pattern. It allows you to create scalable single-page web applications by incorporating common idioms and best practices into the framework. It reduces the time, effort, and resources needed to build any web application. It is focused on making you, the developer, as productive as possible by doing all the common, repetitive, yet essential tasks involved in most web development projects.

Ember uses its own template engine which is a superset of the Handlerbars template engine to build semantic templates effectively with no frustration. The other great thing about ember is that it follows conventions over configuration which helps developers to focus more on their apps, and less on creating your own rules. The popularity of Ember can be measured by its user base. It is used on many popular websites: Yahoo, Netflix, Zendesk, Groupon, LinkedIn and many other major customers.

Vue.js


https://vuejs.org/

Vue (pronounced like view) is a progressive framework for building user interfaces. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only and is very easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is also perfectly capable of powering sophisticated Single-Page Applications when used in combination with modern tooling and supporting libraries.

Vue.js focuses on making ideas in web UI development (components, declarative UI, hot-reloading, time-travel debugging, etc.) more approachable. It attempts to be less opinionated and thus easier for developers to pick up.

Vue was featured as a rising star on GitHub having gained the most stars of any Open Source Project on the popular website. It recently clocked 60,606 stars which makes it among the most popular open source projects on GitHub in general.

Knockout

http://knockoutjs.com/

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.  Knockout is a standalone JavaScript implementation of the Model-View-View-Model pattern. It features:

  • Declarative Binding − HTML DOM elements can be easily associated the model data using concise and readable syntax.
  • Automatic UI Refreshing − Changes made to data model's state are reflected in the UI automatically and vice-versa.
  • Dependency tracking − automatically updates the right parts of your UI whenever your data model changes.
  • Templating − Templates are a way to build complex UI structures. Knockout.js allows you to quickly generate sophisticated, nested UIs as a function of your model data.
  • Extensible - Implement custom behaviors as new declarative bindings for easy reuse in just a few lines of code.


Knockout.js is a compact and pure JavaScript library which can be added on top of your existing web application without requiring major architectural changes.

Backbone.js


http://backbonejs.org/
Backbone.js is a JavaScript framework with a RESTful JSON interface and is based on the model–view–presenter (MVP) pattern. Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface. It features:

  • Ease of developing frontend parts by using JavaScript functions.
  • Automatic refreshing the UI when the model changes.
  • Organized code.

Conclusion

This post briefly talks about the most powerful and popular JavaScript frameworks and libraries. Each of them offers a different way of designing and coding the front-end part of any application. These JavaScript frameworks implement MV* pattern to structure the code, two-way data binding, template engines, and automatic page refreshing when data changes. These frameworks and libraries also differ and have great competition! With so many options available, it becomes difficult to choose the right one. These are must-haves in your skillset as your client may have preferences and you should be ready for it. If you are comfortable with JavaScript, then these are easy to learn!

Check all checkboxes in HTML table using jQuery

Check all checkboxes in HTML table using jQuery
HTML tables are a very handy and useful element. They can adapt to any style or design using CSS and can also hold different input type controls like an input box, checkbox and radio button. This post focuses on having a checkbox in every row of the HTML table, allowing users to select/unselect table rows. So in this quick post, we’ll look at how to check/uncheck all checkboxes in an HTML table using jQuery.

HTML Markup

To get started, create a standard HTML table on the page. For this demo, our table has 4 columns: checkbox in the first column, then Name, Age, and Country, along with some random data. The checkbox is present in the table header as well as in every table row. When the header checkbox is checked, all the checkboxes in the table rows are also checked and vice versa. Here, only the header row checkbox has an ID attribute.

Name Age Country
Maria Anders 30 Germany
Francisco Chang 24 Mexico
Roland Mendel 100 Austria
Helen Bennett 28 UK
Yoshi Tannamuri 35 Canada
Giovanni Rovelli 46 Italy
Alex Smith 59 USA

CSS

The following CSS classes are used to style the table and its rows. There are also styles defined to provide alternate colors to the table rows.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}
td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
th {
  background-color: #ccd;
}
tr:nth-child(even) {
  background-color: #dddddd;
}
tr:nth-child(odd) {
  background-color: #ddeedd;

}

jQuery Code

To implement this functionality, we need to attach a click event to the header checkbox and all the table row checkboxes as well. The solution also takes care of updating the header checkbox status based on the status of the table row checkboxes. The following is the outline of the jQuery solution:

  • First, attach a click event to the header checkbox. In the event, based on its status, check/uncheck HTML table row checkboxes. 
  • Attach a click event handler to all HTML table row checkboxes. In the event, check the clicked checkbox status and header checkbox status. We’ll also need to update the header row checkbox status based on table row checkbox status. If the clicked checkbox status is false and the header checkbox status is true, then uncheck the header checkbox. When the clicked checkbox status is checked, loop through all the other checkboxes to find out if all are checked or not. If all are checked, then also check the header checkbox. 

Here is the complete jQuery code:

$(document).ready(function() {
  $('#chkParent').click(function() {
    var isChecked = $(this).prop("checked");
    $('#tblData tr:has(td)').find('input[type="checkbox"]').prop('checked', isChecked);
  });
  $('#tblData tr:has(td)').find('input[type="checkbox"]').click(function() {
    var isChecked = $(this).prop("checked");
    var isHeaderChecked = $("#chkParent").prop("checked");
    if (isChecked == false && isHeaderChecked)
      $("#chkParent").prop('checked', isChecked);
    else {
      $('#tblData tr:has(td)').find('input[type="checkbox"]').each(function() {
        if ($(this).prop("checked") == false)
          isChecked = false;
      });
      $("#chkParent").prop('checked', isChecked);
    }

  });

 You can see the demo here!

Conclusion

To sum it up, we’ve just learned how to implement check/uncheck checkbox functionality to select HTML table rows based on the header row checkbox status. This solution also updates the header checkbox status based on the status of all the table row’s checkboxes. Based on your needs, you can easily modify this section to take further action on the cell value.

Handling Arrays with jQuery

Handling Arrays with jQuery
An array is a commonly used data structure in any programming language as it can hold a collection of elements, each identified by at least one array index or key. It is the preferred choice for holding multiple values/collections as it allows item sorting, item removal, item retrieval from an array using index, and other useful operations. The array needs to be used properly in code as it may introduce runtime errors (‘index out of the range,’ for example) while accessing any item. This post examines how to implement different array operations using jQuery. Let’s begin.

Check if Variable is an Array

While communicating with the external APIs or third party APIs to fetch data, it’s important to check the type of object, otherwise they can break your code. jQuery provides the $.isArray() method to check if the variable is an array or not. It returns true if the object is an array, otherwise it returns false. It takes a variable name as an argument and returns true/false as a result. Take a look at the following code for reference:

var foo = [];
var bar = ["Apple", "Mango", "Strawberry"];
var baz = "Test";
console.log('foo is an array: ' + $.isArray(foo)); // Returns true
console.log('bar is an array: ' + $.isArray(bar)); // Returns true
console.log('baz is an array: ' + $.isArray(baz)); // Returns false

As you can see, foo and bar are array elements and baz is a variable holding a string value. jQuery.isArray() will return true for foo and bar and false for baz.

Find Index of an Item in Array

To get the index of any item in an array, use the jQuery.inArray() method. The $.inArray() method is similar to JavaScript's native .indexOf() method. It returns the index when a match is found, and -1 when it doesn't find a match. Remember, the index starts from 0 so when the first element matches the searched value, the method returns 0. It accepts 3 parameters: value to search, array variable name, and the optional fromIndex value which indicates the index of the array at which to begin the search. The default is 0, which will search the whole array. Take a look at the following code.

var fruits = ["Apple", "Mango", "Strawberry", "Plum"];
console.log('Index of Apple is: ' + $.inArray("Apple", fruits)); //Returns 0
console.log('Index of Banana is: ' + $.inArray("Banana", fruits)); //Returns -1
console.log('Index of Mango is: ' + $.inArray("Mango", fruits, 2)); //Returns -1

In the last line though mango is in the array, it appears before index 2 so -1 is returned.

Sort an Array

Sorting an array requires calling the JavaScript sort() method on the array object. By default, the sort() method sorts the values as strings in alphabetical and ascending order. It works well for string values, but requires an extra parameter (comparative function) to be passed for numerical values to get the correct sort order. See the below code:

var empfName = ["John", "Adam", "Steve", "Peter"];
empfName.sort() // Will produce Adam, John, Peter, Steve

The default implementation sorts in ascending order, but if descending order is needed, then call reverse() method after the sort() method. Shown here:

var empfName = ["John", "Adam", "Steve", "Peter"];
empfName.sort() // Will produce Adam, John, Peter, Steve
empfName.reverse() // Will produce Steve, Peter, John, Adam

Since the sort() method sorts everything as strings, note that a value like "35" is considered bigger than "135", because "3" is larger than "1". Therefore, to sort a numerical array, you need to pass a compare function. That way when the sort() method compares two values it sends the values to the compare function, and sorts the values according to the returned (negative, zero, or positive) value.

var age = [40, 70, 9, 98];
age.sort(); //Incorrect sort values. 40,70,9,98
age.sort(function(a, b){return a-b}); //Correct sort values. 9,40,70,98

Remove an Item from the Array

To remove an item from an array use the JavaScript splice() method. The splice() method adds/removes items to/from an array and returns the removed item(s). This method needs the index of the item to be removed. Most of the time we don’t know the index, so first we need to determine the index using $.inArray(). See the code:

var empfName = ["John", "Adam", "Steve", "Peter"];
  var nameToRemove = "Adam";
  empfName.splice($.inArray(nameToRemove, empfName), 1);

The first argument is the index of the element to be removed and the second argument denotes the number of items to be removed. If set to 0, no elements will be removed. If you use empfName.splice(1,2), then it will remove 2 items from the array which are at index 1. In this case, the remaining items would be John and Peter. You can also add new items to an array using the splice() method. Like,

empfName.splice(2,0,"Mark");

The above line adds “Mark” to the array at the second index. So now the array items would be, ["John", "Mark”, "Peter"];

Remove Duplicate Items from an Array

There is no in-built method available to remove duplicate items from an array. You may find people using or suggesting jQuery.uniqueSort() or jQuery.unique(), but these methods work only on the array of DOM elements, not strings or numbers. So you need to write your own implementation. The following jQuery code creates a function removeDuplicate which uses jQuery.each and jQuery.inArray() to remove duplicate items. See this code:


function removeDuplicate(arrItems) {
  var newArr = [];
  $.each(arrItems, function(i, e) {
    if ($.inArray(e, newArr) == -1) newArr.push(e);
  });
  return newArr;
}
var numbers = [1, 4, 16, 10, 4, 8, 16];
var newArr = removeDuplicate(numbers);

Once this code is executed, the newArr array will have only unique items.

Merge Two Arrays into a Single Array

If you need to merge the content of two arrays into a single array, use the jQuery.merge() method. This method forms an array that contains all the elements from the two arrays. The order of items in each array is preserved with items from the second array appended. By nature, this method merges the content of two arrays into the first array only. Like so:

var arr1 = [10, 19, 22, 36, 50, 74, 10, 22];
var arr2 = [100,200,300];
var arr3 = $.merge(arr1, arr2);
In this case, the content of arr1 and arr3 would be the same. If you wouldn’t like to alter the content of the first array, then use the following code.
var arr1 = [10, 19, 22, 36, 50, 74, 10, 22];
var arr2 = [100,200,300];
var arr3 = $.merge($.merge([], arr1), arr2);

The inner merge first creates an empty array and clones the content of arr1, then the outer merge copies the content to the newly created array. Note that this does not update the content of the original array.

Conclusion

This post briefly examines some of the common array operations using jQuery’s inbuilt methods. These methods can help to discover any array element, merge two arrays, sort the new array, remove items from the array and remove duplicate items from an array. These methods are easy to use and allow you to implement difficult array operations with ease.

Move Background Image on Mouse-Over Using jQuery

Move Background Image on Mouse-Over Using jQuery
Adding interactive animations can give a fresh look to any website! Many websites use a background image to cover the complete visible screen. Today we'll see how to add an interesting effect on the background image: to move the background image with the mouse cursor movement using CSS and jQuery.

HTML Markup

Let’s start off by creating the HTML markup. Define an empty div element with an ID attribute. We’ll be using the CSS ID selector to create a background image for the page.

CSS

There is an ID based CSS class to create background images with an image URL. This CSS class also sets the position of the image, the width, and the height to 100% in order to make this div fill the entire visible screen with the background image. The CSS property position is set to “fixed” to keep it positioned relative to the browser window.

The image used in this demo is taken from FreeImages.

#background-image {
background: url(http://images.freeimages.com/images/large-previews/08a/street-by-night-1225351.jpg');
position: fixed;
top: 0;
width: 100%;
z-index: 0;
min-height: 100%;
height: auto;
}

jQuery

The jQuery solution is pretty simple and straightforward. Breaking it down, we want to attach a mousemove event on the div element, calculate the new X and Y position based on the current mouse pointer X and Y position, and assign the calculated values as the new background position to the div element.

The following is the outline of the jQuery solution:

  • First, define a variable named “pixelToMove” which holds the value for number of pixels to move on mouse movement. 
  • Attach a mousemove event to div element via jQuery ID selector. In the event, first get the screen width and height and store them in variables. These values will be used to calculate the background movement on X and Y axes. The two variables newValueX and newValueY are used to calculate the movement of the mouse cursor. To calculate, use the current mouse pointer position and then divide by the containers width and height before multiplying them with pixelToMove's variable value. These 2 variables will give us the new top and left position of the background image. 
  • Finally, set the background position property to the value of these variables using jQuery CSS method.

Here is the complete jQuery code:


$(document).ready(function() {
var pixelToMove = 50;
$("#background-image").mousemove(function(e) {
var width = $(this).innerWidth();
var height = $(this).innerHeight();
var newValueX = (e.pageX / width) * pixelToMove;
var newValueY = (e.pageY / height) * pixelToMove;
$(this).css('background-position', newValueX + '%' + ' ' + newValueY + '%');
});
});

You can modify the value of the pixelToMove variable if you want the image to move a greater or lesser number of pixels.

You can check out a working demo here.

Conclusion


We’ve just learned how to move the background image with the mouse cursor movement. Our jQuery solution makes use of the mousemove event on the background wrapper element to calculate the new top and left position for background image and set its background position accordingly. You can modify the jQuery code as per your requirements to increase or decrease the degree of pixel movement. Have fun!

Rotate Text Links using jQuery

Rotate Text Links using jQuery
Rotate Text Links using jQuery Text link ads are a very popular way of monetizing any website. Text link ads are simple links which, upon clicking, will take you to the sponsor’s website. One of the nice feature of text link ads is rotation of the links with smooth animation. In this post, we’ll look at out how to implement rotating text links using jQuery.

HTML Markup

In the HTML, define 3 different anchor tag links. All the anchor tag elements have a CSS class called “links”, which is a dummy class used for selecting these elements using the jQuery CSS class selector.

Google Facebook Twitter

jQuery Code

Next, we’ll need to use JavaScript setInterval(). The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds). You can follow this outline of the jQuery solution:

  • Create an array variable and select all the anchor elements that have CSS class “links”. Hide all the anchor links, except the first one. 
  • Create 2 global variables nTotal and nPos. nTotal will store the array length and nPos will define the index of currently visible link. 
  • Create a function named RotateLinks()
This function will (you guessed it!) rotate the links. The setInteval() method will call this function every 2 seconds. In the function, first slowly fade out the currently visible link. An index of currently visible links is available in the nPos variable, use the eq() method to select that item from the array. Increase the value of the nPos variable by 1 as we need to make the next link visible. You’ll want to ensure that the nPos value does not exceed nTotal. When nTotal and nPos are equal, which means the last link is visible, you’ll want to start the rotation from the first link again by setting the nPos value to 0. Lastly, set the next visible link to fade-in.
Here is the complete jQuery code.

$(document).ready(function() {
  var $anch = $("a.links");
  $anch.hide().eq(0).show();
  var nTotal = $anch.length;
  var nPos = 0;
  setInterval(RotateLinks, 2000);

  function RotateLinks() {

    $anch.eq(nPos).fadeOut("slow", function() {
      nPos++;
      if (nPos == nTotal) {
        nPos = 0;
      }
      $anch.eq(nPos).fadeIn("slow")
    });
  }
});

You can check out the demo here.

An important thing to note is that a callback function must be defined with the fadeOut method. This callback is fired once the animation is complete, and is crucial because if we simply fade out and fade in an overlapping of animation will occur. You can check out the issue yourself by modifying the code like this:

function RotateLinks() {
   $anch.eq(nPos).fadeOut("slow");
   nPos++;
   if (nPos == nTotal) nPos = 0;
       $anch.eq(nPos).fadeIn("slow");
}

The call-back function works like a charm. However, if you wish to have more control over the link transitions, you can use the Cycle plugin. This plugin will accomplish this task in just one line of code. To use the Cycle plug-in, you’ll need to wrap all the anchor tag elements inside a container.
Like:


In jQuery, simply call the cycle() function on the wrapper. Like this:

$(document).ready(function() {
  $('#Links').cycle();
})

You can check out the demo here!

The default transition time is 4 seconds, but you can override this by setting the timeout option. Like so:

$(document).ready(function() { 
  $('#Links').cycle({ 
       timeout : 3000 
  }); 
})

Please visit this link to learn more about the supported operations.

Conclusion

To sum it up, we saw how to rotate text links using jQuery code and the jQuery Cycle plugin. The plain jQuery code uses simple jQuery techniques to rotate the links. You can also control the rotation speed by updating the setInterval() duration. The cycle plugin provides more options to control the link transitions, if you are looking for increased management. Enjoy!