jQuery Tutorial

jQuery is a fast, lightweight JavaScript library that simplifies HTML DOM traversal, event handling, animations, and AJAX. Its motto: "Write less, do more." Still widely used in legacy projects and WordPress.

Setup

HTML
<!-- Include jQuery (CDN) before your scripts -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>

<!-- Your script -->
<script>
  // Ensure DOM is ready before manipulating it
  $(document).ready(function() {
    // jQuery code here
  });

  // Shorthand
  $(function() {
    // Same as document ready
  });
</script>
► Try It Yourself

Selectors

jQuery
// Same as CSS selectors, but wrapped in $()
$("p")           // all <p> elements
$(".btn")        // class selector
$("#myId")       // ID selector (most efficient)
$("ul li")       // descendant
$("a.active")    // combined
$("input[type=text]") // attribute selector
$("tr:even")     // pseudo-selector (even rows)
$("p:first")     // first paragraph
$("p:last")      // last paragraph
$("p:eq(2)")     // 3rd paragraph (0-indexed)
$("li:nth-child(2)") // 2nd list item
$(":visible")    // visible elements
$(":hidden")     // hidden elements
$(":checked")    // checked checkboxes/radios
$(":input")      // all form inputs
$(this)          // current element in callback
► Try It Yourself

Events

jQuery
// .on() - recommended (supports delegation)
$("#btn").on("click", function() {
  alert("Clicked!");
});

// Shorthand event methods
$("#btn").click(function() { ... });
$("input").focus(function() { ... });
$("input").blur(function() { ... });
$("form").submit(function(e) { e.preventDefault(); ... });
$("input").keyup(function(e) { console.log(e.key); });
$("div").mouseover(function() { ... });
$("div").hover(
  function() { $(this).css("color", "red"); },    // mouseenter
  function() { $(this).css("color", "");    }     // mouseleave
);
$(window).on("resize scroll", function() { ... });

// Event delegation (works for dynamically added elements)
$(document).on("click", ".btn", function() {
  alert($(this).text());
});

// Remove event listener
$("#btn").off("click");

// Trigger event
$("#btn").trigger("click");

// event object
$("a").on("click", function(e) {
  e.preventDefault();
  e.stopPropagation();
  console.log(e.target, e.type, e.pageX);
});
► Try It Yourself

DOM Manipulation

jQuery
// Get / Set content
$("#el").text();                  // get text
$("#el").text("New text");        // set text
$("#el").html();                  // get inner HTML
$("#el").html("<b>Bold</b>");     // set inner HTML (XSS risk!)
$("input").val();                 // get input value
$("input").val("New value");      // set input value

// Create and insert
const $div = $("<div>", { class: "card", text: "Hello" });
$("body").append($div);          // insert at END of body
$("body").prepend($div);         // insert at START of body
$("#parent").append("<p>Hi</p>"); // append to element
$div.appendTo("#container");     // alternately
$("#existing").after("<p>After</p>");  // insert after
$("#existing").before("<p>Before</p>"); // insert before

// Remove
$(".temp").remove();             // remove element and events
$(".temp").detach();             // remove but keep events/data
$(".container").empty();         // remove all children

// Copy
const $clone = $("#el").clone(true); // true = deep clone with events
$clone.appendTo("body");
► Try It Yourself

CSS Manipulation

jQuery
// .css() - get/set style
$("p").css("color");              // get
$("p").css("color", "red");       // set
$("p").css({ color: "red", fontSize: "18px", fontWeight: "bold" }); // object

// .addClass() / .removeClass() / .toggleClass()
$("p").addClass("highlight");
$("p").removeClass("old-style");
$("p").toggleClass("active");
$("p").hasClass("active");        // true/false

// Dimensions
$("div").width();         $("div").height();         // content box
$("div").innerWidth();    $("div").innerHeight();     // + padding
$("div").outerWidth();    $("div").outerHeight();     // + border
$("div").outerWidth(true);                            // + margin

// Position & Scrolling
$("div").offset();    // { top: ..., left: ... } relative to document
$("div").position();  // relative to parent
$(window).scrollTop();            // get scroll position
$(window).scrollTop(500);         // set scroll position
► Try It Yourself

Show / Hide / Toggle

jQuery
$("p").hide();                    // display: none
$("p").show();                    // restore display
$("p").toggle();                  // alternates hide/show

// With duration
$("p").hide(400);                 // 400ms animation
$("p").show("slow");              // "slow" (600ms) or "fast" (200ms)
$("p").toggle(500, function() {   // callback after animation
  console.log("Done!");
});

// Fade
$("p").fadeOut();                 // fades out (becomes invisible)
$("p").fadeIn();                  // fades in
$("p").fadeToggle();              // alternates
$("p").fadeTo(500, 0.5);          // fade to 50% opacity in 500ms

// Slide
$("p").slideUp(400);              // animate to height 0
$("p").slideDown("fast");         // animate to full height
$("p").slideToggle();
► Try It Yourself

Animate

jQuery
// .animate() - animate numeric CSS properties
$("div").animate({
  width: "300px",
  height: "200px",
  opacity: 0.5,
  left: "50px"         // needs position: relative/absolute
}, 1000);              // duration in ms

// With easing and callback
$("div").animate({
  fontSize: "24px",
  marginTop: "50px"
}, {
  duration: 800,
  easing: "swing",    // "linear" or "swing"
  complete: function() { console.log("Animation done!"); }
});

// Chaining animations (queue)
$("div")
  .animate({ width: "200px" }, 500)
  .animate({ height: "200px" }, 500)
  .animate({ opacity: 0 }, 500);

// Stop animation
$("div").stop();         // stop current animation
$("div").stop(true);     // clear animation queue
► Try It Yourself

AJAX

jQuery
// $.ajax() - full control
$.ajax({
  url: "https://jsonplaceholder.typicode.com/posts/1",
  type: "GET",           // or POST, PUT, DELETE
  dataType: "json",
  success: function(data) { console.log(data); },
  error: function(xhr, status, err) { console.error(err); },
  complete: function() { console.log("Done"); }
});

// $.get() shorthand
$.get("https://api.example.com/users", function(data) {
  $.each(data, function(i, user) {
    $("ul").append("<li>" + user.name + "</li>");
  });
});

// $.post() shorthand
$.post("/api/contact", {
  name: "Alice",
  message: "Hello!"
}, function(response) {
  alert("Sent!");
});

// $.getJSON() - auto-parse JSON
$.getJSON("/api/products", function(products) {
  console.log(products);
});

// .load() - load HTML fragment into element
$("#content").load("/partials/header.html");
$("#content").load("/page.html #target-div");
► Try It Yourself
Modern Note: For new projects, consider using the native fetch() API and plain JavaScript instead of jQuery. jQuery adds ~30KB of overhead. However, jQuery is still dominant in WordPress themes and legacy codebases.

Event Delegation

Event delegation is critical when elements are added later by AJAX or templating. Instead of binding every button directly, bind once to a stable parent.

jQuery
$('#todoList').on('click', '.remove-btn', function () {
  $(this).closest('li').remove();
});

Plugin Pattern

One reason jQuery stayed popular is its plugin ecosystem. A small plugin wraps repeated behavior into a reusable method.

jQuery
$.fn.highlightCard = function () {
  return this.each(function () {
    $(this).css({ border: '2px solid #0ea5e9', borderRadius: '16px' });
  });
};

$('.feature-card').highlightCard();

Migration Strategy

Many teams maintain jQuery while introducing modern JavaScript gradually. A safe strategy is to replace the simplest utility calls first while leaving the application stable.

  • Replace selectors and class toggles with querySelector and classList.
  • Replace simple AJAX calls with fetch().
  • Keep complex legacy plugins until the surrounding code is stable.