← Back to Chapters

Introduction to jQuery

? Introduction to jQuery

jQuery is a fast, small, and feature-rich JavaScript library. It simplifies HTML document traversal, manipulation, event handling, animation, and Ajax with an easy-to-use API that works across a multitude of browsers. Think of it as a wrapper that makes writing JavaScript much shorter.

? Why Use jQuery?

  • DOM Simplifies traversal and manipulation
  • Compat Handles Cross-browser compatibility issues
  • Brief Reduces the amount of code needed ("Write less, do more")
  • Visuals Built-in animations and fade effects
  • Ajax Simple syntax for dynamic content loading

? Setup & Inclusion

Before writing jQuery, you must include the library in your project (either downloaded or via CDN).

? View Code Example
<!-- Add this inside <head> or before </body> -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

? Syntax & Selectors

The basic jQuery syntax is: $(selector).action()

  • $: Defines/accesses jQuery
  • (selector): Finds HTML elements (e.g., "p", "#id", ".class")
  • .action(): Performs an operation on the element(s)
? View Code Example
// Wait for the document to be fully loaded
$(document).ready(function() {
  
  // Select all paragraph tags and add a click event
  $("p").click(function() {
    
    // 'this' refers to the specific paragraph clicked
    $(this).hide(); 
  });

});

⚙️ Common Actions & Events

jQuery provides simple methods to interact with elements.

Manipulation

  • .html() / .text(): Get or set content
  • .val(): Get or set form input values
  • .css(): Change style properties

Effects

  • .hide() / .show(): Toggle visibility
  • .fadeIn() / .fadeOut(): Smooth opacity transition
  • .slideUp() / .slideDown(): Height transition
? View Code Example
// Select element by ID '#btn' and handle click
$("#btn").click(function(){
    
    // Fade out elements with class '.box'
    $(".box").fadeOut("slow");
    
    // Change text of element with ID '#status'
    $("#status").text("Boxes are fading away...");
});

? Visual Explanation

Imagine you have three red boxes on the screen.

  • Step 1: User clicks the button with ID btn.
  • Step 2: jQuery selects all elements with class .box.
  • Step 3: The boxes slowly decrease in opacity until they vanish (fadeOut).
  • Step 4: The status text updates immediately to inform the user.

? Interactive Example: The "Spoiler" Effect

Click the button below. This demonstrates how easily jQuery handles events (clicking) and effects (sliding) with minimal code.

? View Code Example
// Wait for DOM ready
$(document).ready(function() {

  // Select button by ID and handle click
  $("#demoBtn").click(function() {

    // Toggle slide effect on content box
    $("#demoContent").slideToggle("slow");

    // Optional: Change button text based on current state
    if ( $(this).text().includes("Reveal") ) {
        $(this).text("? Hide Spoiler");
    } else {
        $(this).text("? Reveal Spoiler");
    }
  });
});

? Use Cases

  • Form Validation: Checking if inputs are empty before submission.
  • Interactive UI: Creating dropdown menus, sliders, or accordion tabs.
  • Data Fetching: Using $.get() or $.post() to load data without refreshing the page.

✅ Best Practices

  • Document Ready: Always wrap code in $(document).ready() to ensure the DOM is loaded.
  • Chaining: Link multiple actions in one line: $("#p1").css("color", "red").slideUp(2000).slideDown(2000);
  • Variable Naming: It is common convention to start variables holding jQuery objects with $ (e.g., var $header = $("#header");).
  • Avoid Conflicts: If other libraries use $, use jQuery.noConflict().
  • Efficiency: Don't use jQuery if vanilla JS is just as easy (e.g., modern querySelector).

? Try It Yourself

  • Create an HTML page with a button and a paragraph.
  • Write a script that hides the paragraph when the button is clicked.
  • Build a simple image gallery where clicking a thumbnail uses fadeIn() to show the full image.
  • Use .html() to change a div's content to "Hello World" when the page loads.