DEV Community

Cover image for Why jQuery Exists
sandrockj
sandrockj

Posted on

Why jQuery Exists

What is jQuery and what do you use it for?

The jQuery slogan "write less, do more".

jQuery makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers.

According to W3 Schools:

jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.


Is jQuery still relevant? The short answer is yes!

According to W3 schools, many large corporations use the jQuery libary such as Google, Microsoft, IBM, and Netflix. A StackOverflow survey from last year also indicated that there was still a desire for developers to be experienced with jQuery!

Image description

Alright, so now that we know why jQuery was made, let's see what it is about jQuery that has made web development so much easier. According to the jQuery website, there are four main features and use cases for jQuery:

            1. HTML/DOM Manipulation

            2. CSS Manipulation

            3. HTML Event Methods

            4. AJAX


Traversal & Manipulation of the DOM

First, let's cover what it means to traverse and manipulate the Document Object Model (DOM). Whenever we talk about these kinds of operations you could probably interpret each of them differently, but here is what we mean when we talk about this capability.

  1. Traversing the DOM
    • This is the ability to find elements by their type, class, ID, tags, and more.
    • This is the ability to find an element, and use it to find other elements.
  2. Manipulating the DOM
    • The insertion of new elements to the DOM.
    • This attachment of event listeners to elements existing on the DOM.

jQuery

$( "button.continue" ).html( "Next Step..." )
Enter fullscreen mode Exit fullscreen mode

In this example, jQuery is performing the following actions:

  1. It first traverses the DOM to find an element of tag'button' and class 'continue'.
  2. It then targets the html property of that element and sets it to "Next Step..."

JavaScript

const buttons = document.querySelectorAll("button.continue")

buttons.forEach( (button) => {
    button.innerHTML = "Next Step..."
})
Enter fullscreen mode Exit fullscreen mode

There are quite a few differences between these sets of code, despite them doing the same thing. It's important to note why these two code blocks look different, because something different is happening at each step.

jQuery

  1. jQuery first finds all elements of tag name "button" and class name "continue".
  2. jQuery then returns a newly instanced object, containing references to all elements that we performed a lookup on.
  3. jQuery has an html() method which will attempt to edit all 'referenced' elements in our jQuery object. In particular, this method edits the innerHTML property.

JavaScript

  1. Our native JavaScript finds all elements of tag name "button" and class name "continue".
  2. The querySelectorAll() method returns a NodeList.
  3. Because there is not a native method that acts in the same way as jQuery's html( ) we have to loop through this array-like object and set each button's innerHTML to the desired value.

At this point, it should be pretty apparent that jQuery can save you a lot of time...this is especially true if you are going to have to do operations like this frequently! However, this is just one of the many ways the jQuery enables developers to work more effectively and efficiently.


Manipulation of CSS

There are a lot of reasons why you might need to change an element's CSS on a webpage. Let's give some context to this, because this is actually a lot more important than you might think! If you were an end-user accessing a website on a daily basis, it's likely that you are expecting "feedback" from the website.

Here's an example:

  1. Pretend you are on a social media forum, and you are a moderator.
  2. You ban a user on the page.
  3. The user's name is greyed out and the user's name now has a strikethrough styling.

This is a rough example of editing CSS for feedback, but there are a lot of other applications too. Imagine that you needed to resize or collapse a toolbar on your website; you could just remove that element from the page but you could also edit the CSS properties to change the toolbar's styling.

Now that we have an idea of why someone might need to edit CSS, it should be pretty apparent that we need a way to easily edit an item's CSS. This process is practically identical to that of what we have above.

jQuery

$('button.continue').css('background-color', 'red');
Enter fullscreen mode Exit fullscreen mode

JavaScript

const buttons = document.querySelectorAll('button.continue'); 

buttons.forEach(button => { 
    button.style.backgroundColor = 'red'; 
});
Enter fullscreen mode Exit fullscreen mode

Again, these two functions do the same thing, but it is faster for a developer to work with the jQuery implementation rather than the native JavaScript implementation. It's also important to note that jQuery has many "Effects" methods which can be used to quickly edit an element's CSS properties.


HTML Event Methods

Let's take a look at the code samples provided on the jQuery website, specifically we are going to review how event handling works. If you aren't familiar with events, there are three things to consider with an event: the event listener, the event handler, and the event target.

  • Event listeners are "waiting" for a specific event to occur on an element. This includes hovering your mouse over an element, clicking an element, choosing an option, and more.

  • Event handlers are what actually happens behind the scenes when an event (click, hover, change, etc.) occurs on the page.

  • Event targets are the element which we were "waiting" for an event to happen to.

jQuery

var hiddenBox = $( '#banner-message' );

$('#button-container button').on('click', function(event) {
    hiddenBox.show();
});
Enter fullscreen mode Exit fullscreen mode
  1. In the first line it "targets" a hidden box that it eventually wants to show.
  2. An event listener is added to all buttons under the ID "button-container", and we begin waiting for a "click" event to occur on that button. In this case, each button has an event listener attached to it. Each button is an event target for its unique event listener.
  3. When the event occurs, the event handler uses a jQuery "Effect" to display that banner on the page.

It looks like the jQuery implementation is pretty simple...but can the same be said if we refactored it to use JavaScript?

JavaScript

var hiddenBox = document.getElementById('banner-message'); 
var buttons = document.querySelectorAll('#button-container button'); 

buttons.forEach(function(button) { 
    button.addEventListener('click', function(event) {
        hiddenBox.style.display = 'block';
    }); 
});
Enter fullscreen mode Exit fullscreen mode

Again, jQuery lives up to the expecation of "writing less, doing more"!


Asynchronous JavaScript and XML (AJAX)

If you are unfamiliar with AJAX, W3 Schools simply defines it as a framework which "allows for web pages to be updated asynchronously by exchanging data with a web server behind the scenes". In other words AJAX enables developers to store, and request, data in an existing backend server.

Image description

$.ajax({

  url: "/api/getWeather",

  data: {
    zipcode: 97201
  },

  success: function( result ) {
    $( "#weather-temp" ).html( "<strong>" + result + "</strong> degrees" );
  }

});
Enter fullscreen mode Exit fullscreen mode

In the example above, jQuery is attempting to talk to a server and request weather information for a zip code. On successful receipt of data from the server, it appends the resulting data to the page. It's important to note here that the jQuery $.ajax() method defaults to requesting data, and you would have to specify if you otherwise wanted to send data.

JavaScript

fetch("/api/getWeather?zipcode=97201")

  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.text(); // Assuming the response is text
  })

  .then(result => {
    document.getElementById("weather-temp").innerHTML = `<strong>${result}</strong> degrees`;
  })

  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

Enter fullscreen mode Exit fullscreen mode
  1. The JavaScript fetch() method initiates a request to the server.
  2. The JavaScript then() method checks first to see if the request was received.
  3. Another then() method is chained to the result of the previous, and attempts to append it to the page.
  4. The catch() method is chained to this fetch, and will throw an error if anything goes wrong within the promise chain.

In this case it is a matter of preference, but personally I find myself more accustomed to using jQuery to handle AJAX operations. Overall these implementations are quite different in syntax, and if you choose to use jQuery for handling AJAX operations more documentation can be found at this link.


Conclusion

I hope that your understanding of jQuery has improved after reading this post! In my own experience, jQuery is a powerful tool that has made performing tasks much easier. If you do choose to learn more about jQuery, their website includes all documentation!

Top comments (0)