Skip to content

jQuery

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, and animation much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way millions of people write JavaScript.

jQuery is Legacy Technology

Important: jQuery is now considered legacy technology and is not recommended for new projects. Modern JavaScript (ES6+) and native browser APIs now provide all the functionality jQuery offered, often with better performance and no dependencies.

When to use jQuery:

  • Maintaining existing jQuery-based projects
  • Working with legacy codebases that depend on jQuery
  • Supporting very old browsers (IE8 and below)

For new projects, use vanilla JavaScript or modern frameworks (React, Vue, Svelte) instead.

Historical Context

jQuery was created in 2006 by John Resig and became extremely popular because it solved major problems at the time:

Problems jQuery solved (in 2006-2015):

  • Massive browser inconsistencies (especially Internet Explorer)
  • Verbose DOM manipulation in vanilla JavaScript
  • Complex cross-browser event handling
  • Difficult Ajax implementation
  • No native animation support

Why it’s less relevant today:

  • Modern browsers follow standards consistently
  • Native JavaScript APIs are now simple and powerful
  • ES6+ features make JavaScript cleaner
  • Modern frameworks handle complexity better
  • jQuery adds ~30KB to page load (unnecessary overhead)

Why jQuery Was Important

Simplicity:

jQuery simplified complex tasks in JavaScript, allowing developers to achieve more with less code.

Cross-Browser Compatibility:

One of the main reasons for jQuery’s popularity was its ability to handle cross-browser issues developers encountered, especially with older Internet Explorer versions.

Extensibility:

With a vast ecosystem of plugins, developers could easily extend jQuery’s capabilities.

Ajax Support:

jQuery provided a robust set of Ajax methods that simplified server communication.

Core Features of jQuery

DOM Manipulation:

Easily select elements, traverse the DOM, and modify content.

Event Handling:

Attach events to elements without worrying about browser inconsistencies.

Animations and Effects:

Slide, fade, and animate elements with just a few lines of code.

Ajax:

Simplified methods for making asynchronous HTTP requests.

Utilities:

A collection of utility functions such as $.each, $.extend, and more.

Getting Started with jQuery

To use jQuery, you need to include it in your HTML. You can either download it or use a CDN:

CDN (recommended for learning):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Example</title>
</head>
<body>
    <h1>Hello jQuery</h1>
    <button id="myButton">Click me</button>

    <!-- Include jQuery from CDN -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    <script src="app.js"></script>
</body>
</html>

NPM (for build systems):

npm install jquery
import $ from 'jquery';

Basic Syntax

jQuery uses the $ symbol as its main function. The basic syntax is:

$(selector).action()

Where:

  • $ - Accesses jQuery
  • selector - Finds HTML elements
  • action() - Action to perform on the element(s)

Selecting Elements

jQuery uses CSS selectors to find elements:

Basic selectors:

// By element type
let paragraphs = $("p");

// By ID
let header = $("#myHeader");

// By class
let items = $(".item");

// Multiple selectors
let elements = $("p, .item, #myDiv");

// Descendant selector
let listItems = $("ul li");

// Direct child
let directChildren = $("ul > li");

Modern vanilla JavaScript equivalent:

// jQuery
let elements = $(".item");

// Vanilla JS (same result)
let elements = document.querySelectorAll(".item");

DOM Manipulation

Changing Content

Getting and setting content:

// Get text content
let text = $("#myDiv").text();

// Set text content
$("#myDiv").text("New text");

// Get HTML content
let html = $("#myDiv").html();

// Set HTML content
$("#myDiv").html("<strong>Bold text</strong>");

// Get input value
let value = $("#myInput").val();

// Set input value
$("#myInput").val("New value");

Vanilla JavaScript equivalent:

// jQuery
$("#myDiv").text("New text");

// Vanilla JS
document.querySelector("#myDiv").textContent = "New text";

Changing Attributes and Styles

// Get attribute
let src = $("img").attr("src");

// Set attribute
$("img").attr("src", "new-image.jpg");

// Set multiple attributes
$("img").attr({
    src: "new-image.jpg",
    alt: "New Image"
});

// Change CSS
$("#myDiv").css("color", "red");

// Set multiple CSS properties
$("#myDiv").css({
    color: "red",
    fontSize: "20px",
    backgroundColor: "#f0f0f0"
});

Vanilla JavaScript equivalent:

// jQuery
$("#myDiv").css("color", "red");

// Vanilla JS
document.querySelector("#myDiv").style.color = "red";

Adding and Removing Classes

// Add class
$(".item").addClass("active");

// Remove class
$(".item").removeClass("active");

// Toggle class
$(".item").toggleClass("active");

// Check if has class
if ($(".item").hasClass("active")) {
    console.log("Item is active");
}

Vanilla JavaScript equivalent:

// jQuery
$(".item").addClass("active");

// Vanilla JS
document.querySelectorAll(".item").forEach(item => {
    item.classList.add("active");
});

Adding and Removing Elements

Adding Elements

jQuery provides several methods to add new elements:

append():

Inserts content at the end of the selected elements.

prepend():

Inserts content at the beginning of the selected elements.

after():

Inserts content after the selected elements.

before():

Inserts content before the selected elements.

// Add a new list item at the end of a list
$("ul").append("<li>New Item at the end</li>");

// Add a new list item at the beginning of a list
$("ul").prepend("<li>New Item at the start</li>");

// Add a paragraph after a specific div
$("#myDiv").after("<p>New paragraph after the div</p>");

// Add a paragraph before a specific div
$("#myDiv").before("<p>New paragraph before the div</p>");

Vanilla JavaScript equivalent:

// jQuery
$("ul").append("<li>New Item</li>");

// Vanilla JS
document.querySelector("ul").insertAdjacentHTML("beforeend", "<li>New Item</li>");

Removing Elements

remove():

Removes the selected element(s) and its child elements.

empty():

Removes the child elements from the selected element(s).

// Remove a specific list item
$("#itemToRemove").remove();

// Empty the content of a div
$("#contentDiv").empty();

// Remove all paragraphs
$("p").remove();

Vanilla JavaScript equivalent:

// jQuery
$("#itemToRemove").remove();

// Vanilla JS
document.querySelector("#itemToRemove").remove();

Event Handling

jQuery provides a unified way to handle events across browsers.

Basic event binding:

// Click event
$("#myButton").click(function() {
    alert("Button was clicked!");
});

// Hover events
$("#myDiv").hover(
    function() {
        // Mouse enter
        $(this).css("background-color", "yellow");
    },
    function() {
        // Mouse leave
        $(this).css("background-color", "white");
    }
);

// Multiple event handlers
$("#myButton").on({
    click: function() {
        console.log("Clicked");
    },
    mouseenter: function() {
        console.log("Mouse entered");
    },
    mouseleave: function() {
        console.log("Mouse left");
    }
});

Event delegation:

// Event delegation for dynamically added elements
$("ul").on("click", "li", function() {
    console.log("List item clicked:", $(this).text());
});

Vanilla JavaScript equivalent:

// jQuery
$("#myButton").click(function() {
    alert("Button clicked!");
});

// Vanilla JS
document.querySelector("#myButton").addEventListener("click", function() {
    alert("Button clicked!");
});

Form Events

// Form submission
$("#myForm").submit(function(event) {
    event.preventDefault(); // Prevent default form submission

    let username = $("#username").val();
    console.log("Username:", username);
});

// Input change
$("#myInput").change(function() {
    console.log("Value changed to:", $(this).val());
});

// Input (fires on every keystroke)
$("#myInput").on("input", function() {
    console.log("Current value:", $(this).val());
});

Animations and Effects

With jQuery, adding animations is straightforward.

Basic effects:

// Hide element
$("#myDiv").hide();

// Show element
$("#myDiv").show();

// Toggle visibility
$("#myDiv").toggle();

// Fade in
$("#myDiv").fadeIn("slow");

// Fade out
$("#myDiv").fadeOut("fast");

// Fade to specific opacity
$("#myDiv").fadeTo("slow", 0.5);

// Slide down
$("#myDiv").slideDown("slow");

// Slide up
$("#myDiv").slideUp("fast");

// Slide toggle
$("#myDiv").slideToggle();

Custom animations:

// Animate to specific CSS properties
$("#myDiv").animate({
    left: "250px",
    opacity: 0.5,
    height: "150px",
    width: "150px"
}, "slow");

// Chaining animations
$("#myDiv")
    .slideUp("slow")
    .slideDown("slow")
    .fadeOut("slow")
    .fadeIn("slow");

Vanilla JavaScript equivalent:

Modern JavaScript uses CSS transitions/animations or the Web Animations API:

// jQuery
$("#myDiv").fadeOut("slow");

// Vanilla JS with CSS
element.style.transition = "opacity 0.5s";
element.style.opacity = "0";

// Or Web Animations API
element.animate([
    { opacity: 1 },
    { opacity: 0 }
], {
    duration: 500
});

Ajax

jQuery simplifies the process of making Ajax requests.

Basic GET request:

$.ajax({
    url: "data.json",
    type: "GET",
    dataType: "json",
    success: function(data) {
        console.log(data);
    },
    error: function(error) {
        console.error("Error:", error);
    }
});

// Shorthand GET method
$.get("data.json", function(data) {
    console.log(data);
});

// Even shorter with getJSON
$.getJSON("data.json", function(data) {
    console.log(data);
});

POST request:

$.ajax({
    url: "submit.php",
    type: "POST",
    data: {
        name: "John",
        email: "john@example.com"
    },
    success: function(response) {
        console.log("Success:", response);
    },
    error: function(error) {
        console.error("Error:", error);
    }
});

// Shorthand POST method
$.post("submit.php", { name: "John" }, function(response) {
    console.log(response);
});

Vanilla JavaScript equivalent:

// jQuery
$.getJSON("data.json", function(data) {
    console.log(data);
});

// Vanilla JS with Fetch API
fetch("data.json")
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error("Error:", error));

jQuery Utilities

jQuery provides helpful utility functions:

// Loop through array
$.each([1, 2, 3], function(index, value) {
    console.log(index, value);
});

// Loop through object
$.each({ name: "John", age: 30 }, function(key, value) {
    console.log(key, value);
});

// Extend objects
let defaults = { color: "red", size: "medium" };
let options = { size: "large" };
let settings = $.extend({}, defaults, options);
// Result: { color: "red", size: "large" }

// Check if element is array
$.isArray([1, 2, 3]); // true

// Trim whitespace
$.trim("  hello  "); // "hello"

// Map array
let doubled = $.map([1, 2, 3], function(value) {
    return value * 2;
}); // [2, 4, 6]

Extending jQuery with Plugins

jQuery can be extended with custom plugins:

// Define a custom jQuery plugin
$.fn.changeTextColor = function(color) {
    return this.css("color", color);
};

// Usage
$("p").changeTextColor("red");

// Plugin with options
$.fn.highlight = function(options) {
    let settings = $.extend({
        backgroundColor: "yellow",
        color: "black"
    }, options);

    return this.css({
        backgroundColor: settings.backgroundColor,
        color: settings.color
    });
};

// Usage
$("p").highlight({ backgroundColor: "lime" });

jQuery vs Modern JavaScript

Here’s a comparison showing why vanilla JavaScript is now preferred:

Task jQuery Vanilla JS (Modern)
Select element $("#id") document.querySelector("#id")
Select all $(".class") document.querySelectorAll(".class")
Add class $(el).addClass("active") el.classList.add("active")
Set text $(el).text("Hi") el.textContent = "Hi"
Set HTML $(el).html("<b>Hi</b>") el.innerHTML = "<b>Hi</b>"
Click event $(el).click(fn) el.addEventListener("click", fn)
Ajax GET $.get(url, fn) fetch(url).then(r => r.json()).then(fn)
Loop array $.each(arr, fn) arr.forEach(fn)
File size ~30KB 0KB (native)

Performance comparison:

// jQuery (slower)
$(".item").each(function() {
    $(this).addClass("active");
});

// Vanilla JS (faster)
document.querySelectorAll(".item").forEach(item => {
    item.classList.add("active");
});

When You Might Still Need jQuery

Working with legacy projects:

Many existing websites use jQuery, and you’ll need to maintain them.

Using jQuery plugins:

Some older plugins (date pickers, sliders, etc.) still require jQuery.

Supporting very old browsers:

If you need to support IE8 and below (very rare now).

Large existing codebase:

Rewriting everything might not be feasible.

Migrating from jQuery

If you’re maintaining a jQuery project and want to gradually migrate:

  1. Start with new features - write them in vanilla JS
  2. Replace jQuery calls one module at a time
  3. Use tools like You Might Not Need jQuery for reference
  4. Test thoroughly after each change
  5. Consider modern frameworks for complex applications

Summary

jQuery was revolutionary in its time but is now considered legacy technology. Modern JavaScript provides all the same functionality with better performance and no dependencies.

Key Takeaways

Historical Importance:

  • Solved cross-browser compatibility issues (especially IE)
  • Made DOM manipulation simple when vanilla JS was verbose
  • Unified event handling across browsers
  • Simplified Ajax when native APIs were complex
  • Huge ecosystem of plugins

Core Features:

  • DOM manipulation: Select and modify elements easily
  • Event handling: Unified event API with delegation
  • Animations: Built-in effects and custom animations
  • Ajax: Simplified server communication
  • Utilities: Helper functions for common tasks

Why It’s Legacy:

  • Modern browsers are consistent (no IE issues)
  • Native JavaScript is now simple and powerful
  • Adds 30KB+ to page load unnecessarily
  • Modern frameworks handle complexity better
  • Performance overhead vs vanilla JS

Modern Alternatives:

  • Vanilla JS: For simple DOM manipulation
  • Fetch API: For Ajax requests
  • CSS animations: For effects and transitions
  • React/Vue/Svelte: For complex applications

When to Still Use jQuery:

  • Maintaining existing jQuery projects
  • Working with jQuery-dependent plugins
  • Supporting very old browsers (IE8-)
  • Not recommended for new projects

Migration Tips:

  • Learn vanilla JS equivalents
  • Use You Might Not Need jQuery
  • Migrate gradually, module by module
  • Test thoroughly
  • Consider modern frameworks for rewrites

Common jQuery Patterns:

// Selecting
$("#id")                            document.querySelector("#id")

// Events
$(el).click(fn)                     el.addEventListener("click", fn)

// Content
$(el).text("hi")                    el.textContent = "hi"

// Classes
$(el).addClass("active")            el.classList.add("active")

// Ajax
$.get(url, fn)                      fetch(url).then(r=>r.json()).then(fn)

Understanding jQuery is valuable for maintaining legacy code, but for new projects, invest your time in learning modern JavaScript and current frameworks instead.