jQuery

jQuery Complete Tutotial

In this blog, I will explain jQuery. We all know that jQuery is a JavaScript library and is easy to use, but apart from that, you need to understand how jQuery works and how to write efficient jQuery code. Anyone can write code, but a real developer writes optimized code.

What is jQuery?

jQuery is a fast, small, and feature-rich JavaScript library. Its primary purpose is to make it easier to work with the Document Object Model (DOM), reducing the amount of code required for common tasks.

Why use jQuery?

jQuery streamlines web development, making it faster and more efficient, particularly for developers working with older browsers or those looking to quickly implement dynamic features.

1. Ease of Use: 

jQuery simplifies common tasks in JavaScript, allowing you to write less code and get more done.

// Without jQuery (Vanilla JavaScript):
document.getElementById('myElement').style.display = 'none';
document.getElementById('myElement').innerText = 'New Text';
document.getElementById('myElement').classList.add('active');

//With jQuery:
$('#myElement').hide();
$('#myElement').text('New Text');
$('#myElement').addClass('active');

2. Cross-browser Support: 

Cross-browser support means that jQuery ensures the same JavaScript code behaves consistently across different web browsers. Browsers like Chrome, Firefox, Safari, Edge, and Internet Explorer all interpret JavaScript slightly differently. Without jQuery, developers often had to write multiple lines of code or use hacks to accommodate these differences.

jQuery abstracts these browser inconsistencies and provides a unified way to interact with web elements, making it easier to develop cross-browser web applications.

Real-time Example: Let’s say you want to add an event listener to a button that triggers an alert when clicked. Different browsers may have different ways of handling events, especially in older browsers like Internet Explorer (IE).

Without jQuery (Vanilla JavaScript):
var button = document.getElementById('myButton');

// Event handling for modern browsers
if (button.addEventListener) {
    button.addEventListener('click', function() {
        alert('Button clicked!');
    });
} 
// Event handling for older Internet Explorer versions (IE8 and below)
else if (button.attachEvent) {
    button.attachEvent('onclick', function() {
        alert('Button clicked!');
    });
}

In this code: For modern browsers, we use addEventListener to attach the event. For older browsers like Internet Explorer 8 and below, we have to use attachEvent. This means you have to check for browser support and write conditional code, which can get cumbersome.

With jQuery (Cross-browser Support Automatically Handled):

$('#myButton').on('click', function() {
    alert('Button clicked!');
});

In jQuery: The on() method automatically handles the cross-browser differences behind the scenes. You don’t need to worry about whether you’re using a modern browser or an older version of Internet Explorer.
The code is simpler and more concise, and it works across all browsers without the need for extra conditional logic.

3. Rich Ecosystem: 

There are many plugins built on top of jQuery that allow you to extend its capabilities even further (like carousels, date pickers, etc.).

Though jQuery was extremely popular in the past, modern JavaScript (with features like querySelector, fetch, async/await, and others) has made a lot of what jQuery provides unnecessary. However, it's still widely used in many existing projects and websites.

jQuery Object

When you call $('elem'), you're not just selecting the element itself. You're getting a jQuery object, which has methods and properties that allow you to manipulate the selected elements.

// Native JavaScript: Selects an element
const element = document.getElementById('myElement');

// jQuery: Selects the element and wraps it in a jQuery object
const $element = $('#myElement');

Here, $element is not just the DOM element itself but a jQuery object. This object has multiple methods that can be chained together.

How jQuery Object Works:

The $() function always returns a jQuery object. This object contains methods like find, attr, css, etc.

// Using jQuery to find an element, change its attribute, and set its CSS
$('#myElement')
  .attr('title', 'New Title') // Changes the title attribute
  .css('color', 'blue') // Changes the text color to blue
  .find('.childElement') // Finds a child element
  .text('Updated Text'); // Updates the text of the child element

jQuery is object-oriented in the sense that the jQuery object ($('elem')) provides a set of methods (like css, attr, find) that act like key-value pairs (methods as "keys" and functionality as "values"). Think of it like you're calling a single object that contains multiple functions, each designed to perform different tasks on the selected elements.

{
  css: function() { /* some code */ },
  attr: function() { /* some code */ },
  find: function() { /* some code */ },
  // and so on...
}

Efficiency Consideration:

Every time you call $('elem'), you're creating a new jQuery object. Even if you're selecting the same element multiple times, each call to $('elem') creates a new object with its own methods.

// First time calling $('#myElement')
$('#myElement').css('color', 'red');

// Second time calling $('#myElement') to get the same element
$('#myElement').attr('title', 'New Title');

If you keep calling $('elem') for the same element multiple times, it means you're creating a new jQuery object each time. This can have a small performance impact, especially in a large-scale application.

Optimized Approach: Instead of calling $('elem') repeatedly, you can store the jQuery object in a variable and reuse it.
// Store the jQuery object once
var $element = $('#myElement');

// Reuse the object for multiple manipulations
$element.css('color', 'red');
$element.attr('title', 'New Title');
$element.find('.childElement').text('Updated Text');
In this case, you're only calling $('#myElement') once, and then you're interacting with the same jQuery object multiple times, which is more efficient.

Thank You!