JavaScript-Equivalent jQuery Code for Simple Tasks

Introduction

There are developers who love jQuery and there are some who hate jQuery. The benefits of using jQuery now are debatable, but there was a time when solving the cross-browser issue was a nightmare and using JavaScript was painful. If you had been through that phase, you might understand the importance of jQuery. jQuery was born to overcome the biggest issues of JavaScript. Over the years, JavaScript has also evolved but we should be thankful for the fact that modern browsers are also becoming more and more standard-compliant. jQuery is still a powerful library and it can still reduce your efforts for client-side programming.

The aim of this post is not to discourage your use of JavaScript, but rather to give you an insight into how jQuery can help to solve simple tasks compared to JavaScript. jQuery can help in reducing the lines of code and your efforts, lessen cross-browser compatibility issues, result in faster development, and it makes AJAX calls and animations dead simple. To start with, we'll take a look at the most basic requirements like selecting elements on the page by their ID, class, and tag name and then we will look at some complex examples. Let’s dive in!

Selecting an Element by ID

JavaScript code

document.querySelector('#elmID'); // Modern Way - IE8 and above 
document.getElementById('elmID'); // Older Way 

jQuery code

$('#elmID');

As you can already see, we've used less code to select the element in jQuery.

Selecting an Element by Tag

Consider a use case to select all the paragraph elements on the page:

JavaScript code

document.getElementsByTagName('p'); 

jQuery code

$('p');

Again, shorter code in jQuery!

Selecting Elements by Class Name

To select all elements having dummy CSS class:

JavaScript code

document.getElementsByClassName('dummy'); // Older Way 
document.querySelectorAll('.dummy'); // Modern Way - IE8 and above

jQuery code

$('.dummy');

We can see a continuing trend of fewer and shorter lines of code in jQuery.

Change Body Background Color on Load

JavaScript code

function changeBackground(color) {
    document.body.style.background = color;
}
<body onload = "changeBackground('green');" >

jQuery code

$ ('body').css('background-color', 'green');

A single line of code accomplishes what takes four lines of code to accomplish in JavaScript.

Adding a CSS Class to Element

JavaScript code

if (el.classList)
  el.classList.add(className);
else
  el.className += ' ' + className;

jQuery code

$(el).addClass(className);

That's three fewer lines!

Making an Ajax Call

JavaScript code

function loadValues() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById(“demo”).innerHTML = this.responseText;
        }
    };
    xhttp.open(“GET”, “/api/values”, true);
    xhttp.send();
}

jQuery code

function loadValues() {
    $.ajax({
        url: "/api/values",
        type: "GET",
        dataType: "json",
        success: function(data) {
            $('#demo').html(data);
        },
        error: function(response) {
            alert(response.responseText);
        }
    });
}

The jQuery version looks much cleaner and more readable, it also offers a better method for error handling.

Making a Simple Fade-Out Animation

JavaScript code

function fadeOut(element) {
    var op = 1; // initial opacity
    var timer = setInterval(function() {
        if (op < = 0.1) {
            clearInterval(timer);
            element.style.display = ‘none’;
        }
        element.style.opacity = op;
        element.style.filter = ‘alpha(opacity = ’+op * 100 + “)”;
        op -= op * 0.5;
    }, 500);
}
var element = document.getElementById(‘elm’);
fadeout(element);

jQuery code

$("#elm").fadeOut();

There is no need to judge here who is better: jQuery is the clear winner.

Conclusion

We’ve just seen how jQuery can make life much simpler for easy tasks. Some functionality can be achieved by just one line of code in jQuery that requires 15-20 lines of JavaScript to achieve the same result. jQuery is an awesome library and it’s still very popular among developers. You should consider it as an alternative for fast development and without worrying about cross-browser issues. However, you should also be careful as it's large file to load! 



Responsive Menu
Add more content here...