How to REALLY Learn JavaScript Series: Part 7 From JavaScript to jQuery

Continuing on in our JavaScript series I will introduce you to jQuery. In most cases, newcomers to the language will be doing this the opposite way this series is authored. By this I mean, a lot of developers new to JavaScript start off with jQuery rather than vanilla JavaScript to learn the language. I too took this journey but always found myself wondering how certain functions, methods, expressions and more worked inside of jQuery without seeing the legacy code in plain JavaScript.

Chances are, you have already been exposed to jQuery if you’re reading this post. I’m merely going to explain some differences in the syntax even though all the code you’ll see is still JavaScript. jQuery is JavaScript.

Why Use jQuery?

Modern developers make use of jQuery often. In fact, most websites on the world wide web are using jQuery or JavaScript in some shape or form. You can think of jQuery as a condensed version of JavaScript. Inside you can call upon HTML elements to provide some notion of interactivity, event handling, animation, and Ajax if required. jQuery makes this easy with a simpler syntax and a multitude of bundled methods to help you easily achieve what you need with minimal code.

Browser Support

Another big plus for jQuery is its browser support. JavaScript by nature comes ready to use in most browsers dating pretty far back ( ex. IE6). jQuery too supports the same browsers which is huge for modern day developers since we have to make our code universal across many platforms and devices. With jQuery available, developers can now rest assured knowing what they author with jQuery should work across all applications.

Chaining

In jQuery, you can chain code and it is awesome. Within the API, jQuery has many methods available to you that can be chained together to manipulate any HTML within your page consecutively. Every method works hand in hand to do what you’re trying to achieve. Check out this example:

$('#button').on("click", function(){
  $(this)
    .css({ 'background': 'green', 'color': 'yellow' })
      .html("Button Text Changes")
    .animate({ top: '50px', left: '0px' })
    .fadeOut(3000)
});

See the Pen OVXOKZ by Andy Leverenz (@justalever) on CodePen.

Chaining works with a simple dot notation. Each method is chained by continuously adding more and more methods to a function or event in which you declare. Above I simply chain methods like this


// Easy chaining
.css(...).html(...).animate(...).fadeOut()

It’s Easy

There’s no doubt about it that jQuery is much easier to use out of the box than traditional JavaScript but that doesn’t always mean it’s the perfect choice for your application. If you can get away without loading jQuery inside your project I highly recommended coding with vanilla Javascript to contribute to better load times on your website or application.

Ajax

jQuery supports Ajax. This too is awesome and relatively easy to setup. What looks like a daunting task in traditional JavaScript can be achieved easily with jQuery. Below is an example using jQuery’s support Ajax methods. There is much more you can do with this but essential what is happening is that the file test.html is being appended into the #results div. You can do this using jQuery by targeting a click event for example.


$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

A lot of different data can be sent to and from server-side and client side applications. Ajax combined with JSON can allow developers to achieve some amazing results with jQuery.

Making the Transition

JavaScript and jQuery are the same language. They may appear to be different, but each can achieve the same results. Below I’ll show you a kind of before and after effect on some typical code you use often in both languages.

Querying the DOM

JavaScript
Selecting an element in JavaScript typically happens like this:

var myElement = document.getElementById('#myElement');

Inside your HTML you assign an id to an element you want to target with JavaScript. Doing so gives you quick access to that element in particular though there are other ways to target it without supplying an id.

A more modern approach is written like this:

var myElement = document.querySelector('#myElement');

jQuery
jQuery makes it easy in just a few characters. Selecting an element in the DOM takes place like this:

var myElement = $(‘#myElement’);

This function will query the DOM for the element with an id of myElement and create a new jQuery object (defined by the $ character).

Querying multiple elements

There’s going to be a time where you need to select more than one element at once. Doing so is pretty straight forward but authored in different ways

JavaScript
In vanilla JavaScript, you query the DOM using the querySelectorAll method. Doing so returns all elements that match whatever CSS selector you supply.

var myList = document.querySelectorAll(‘#myElement li’);

This may cause you to run into problems with certain versions of Internet Explorer. If you want to go the old school approach you can with:

var myList = document.getElementById('myElement').getElementsByTagName('li');

jQuery
jQuery makes it simple again by using CSS selectors that you’re already using in your HTML


// all list items inside #myElement div
var myList = $('#myElement li');

Event Listeners

Event listeners come in very handy in the world of the web. Upon clicking something users expect something to take place immediately or at least indicate something will happen.

JavaScript
Below I query the DOM for an id of myButton of which I append an onclick method to. We pass it a parameter of e which is just a placeholder for our event being fired. From there you can author some more functionality. I included a stopPropagation() method to keep the event from bubbling up the DOM tree.


document.getElementById('myButton').onclick = function(e) {
    e.stopPropagation();
    // Do something 
}

jQuery
As you could expect, this gets easier with jQuery:


$('myButton').on('click', function(e){   
    e.stopPropagation();
    // Do Something 
});

DOM Injection

Ever need to insert an element or attribute to dynamically? Sometimes you just need that extra kick to get your web pages to be that much more interactive.

JavaScript
Let’s start by adding attributes to elements that already exist within the HTML.


function addClass(elem, className) {
    if (!hasClass(elem, className)) {
        elem.className += ' ' + className;
    }
}

document.getElementById('myButton').onclick = function() {
    addClass(document.documentElement, 'some-class');
}

In JavaScript you need to define a function to enable the proper usage of adding an attribute that is a class. Here I created a function that has two parameters. You supply the element to add the class to as well as the class name itself. You may notice the property document.documentElement. This simply refers to the parent document you are targeting in the first place. So in our case it is myButton.

jQuery
jQuery does a lot of the work for you. You don’t need to define a function to add a class but simply use the addClass() method like this:

$('#myButton').addClass('myClass');

Adding elements is similar to attributes. Doing so requires a few new properties and methods but it’s fairly straight forward.

JavaScript
In JavaScript appending an element to a page requires a bit of setup but each line below allows you to customize whatever element you need to add.


// Setup
var myDiv = document.createElement('div');
div.id = "box";
div.innerHTML = "My neat new div";

// Append the div to the page
document.body.appendChild(div);

jQuery
With jQuery, you can write HTML within your script to inject into whatever part of the DOM you like. Doing that looks something like this:

$('<div id="box"></div>').appendTo('body');

DOM Ready Execution

You can trigger your JavaScript to load after the DOM has loaded. This helps with certain events or interactions you define in the language.

JavaScript
As part of HTML5, you can use the DOMContentLoaded event inside an event listener query.


document.addEventListener('DOMContentLoaded', function() {
    // Do something 
});

jQuery
In jQuery you’ll likely see this a lot:


$(document).ready(function(){
    // Do stuff after the DOM loads
});

Going Further

There’s virtually endless amounts of things you can do with jQuery and JavaScript. Be careful when combining both sets of syntax because conflicts can occur. jQuery is a great tool to use if you need to write fast and efficient code. The major downfall is always having to link to the library even though it’s a tiny library which doesn’t typically reflect poor load times.

If you’re new to JavaScript I think it’s important to understand where jQuery came from. You should try and at least look at the source code within the library to see how the functionality is set in place. Doing so will help you understand how to best author any jQuery in the future.

If you’re following this series you’ll likely noticed I did things backwards. I did this on purpose so you can gain a grasp of traditional JavaScript before jumping into jQuery and not necessarily know what you’re doing. There’s plenty I haven’t covered so you’ll need to do some homework of your own by building out your won examples using the ample amount of methods available to you. As with anything, you learn better by doing so get out there and build something.

Going forward in the series we will dive into more modern JavaScript frameworks and best practices. I’ll discuss things such as templating, single page web applications, and more. Stay tuned!

The Series So Far