CoachingUgosay

Web Development - jQuery Documentation

The Write less and Do more for Javascript library

Quick Navigation

Why jQuery?

jQuery simplifies HTML document traversing, event handling, and Ajax interactions.

CDN Linkhttps://code.jquery.com/jquery-3.6.0.min.js
$(document).ready(function() {
$("button").click(function() {
$("p").slideToggle();
});
});

Powerful Selectors

jQuery selectors allow you to select and manipulate HTML elements

Basic Selectors

$("p")

Selects all <p> elements

$("#demo")

Selects element with id='demo'

$(".test")

Selects elements with class='test'

Attribute Selectors

$("[href]")

Selects elements with href attribute

$("[href='default.htm']")

Selects elements with exact href value

$("[href*='fueint']")

Selects elements with href containing 'fueint'

Hierarchy Selectors

$("div p")

Selects all <p> inside <div>

$("div > p")

Selects <p> directly inside <div>

$("div + p")

Selects <p> immediately after <div>

Interactive Events

jQuery provides elegant methods for handling user interactions with clean, intuitive syntax

1Mouse Events

click
$(selector).click(function)
dblclick
$(selector).dblclick(function)
hover
$(selector).hover(inFunction, outFunction)
mousedown
$(selector).mousedown(function)
mouseup
$(selector).mouseup(function)

2Keyboard Events

keypress
$(selector).keypress(function)
keydown
$(selector).keydown(function)
keyup
$(selector).keyup(function)

3Form Events

submit
$(selector).submit(function)
change
$(selector).change(function)
focus
$(selector).focus(function)
blur
$(selector).blur(function)
select
$(selector).select(function)

4Document Events

ready
$(document).ready(function)
load
$(window).load(function)
unload
$(window).unload(function)
resize
$(window).resize(function)
scroll
$(window).scroll(function)

Pro Tip: Event Delegation

For dynamic elements, use $(document).on('click', '.selector', function) instead of direct binding. This ensures events work for elements added after page load.

jQuery Effects

Create smooth animations and transitions with jQuery effect methods

Display Effects

.hide()
.show()
.toggle()

Slide Effects

.slideDown()
.slideUp()
.slideToggle()

Fade Effects

.fadeIn()
.fadeOut()
.fadeTo()
.fadeToggle()

Other Effects

.animate()
.delay()

Effect Syntax

$(selector).show([speed, callback]);

Speed Parameters

  • Words: slow, "normal", "fast"
  • Milliseconds: 1000 (1 second)

Callback Function

Executes after animation completes. Called once per animated element.

Example Usage

// Fade out with callback
$("#box").fadeOut("slow", function() {
console.log("Animation complete");
});
// Slide toggle with speed
$(".panel").slideToggle(500);
// Custom animate
$(".item").animate({
left: "250px",
opacity: "0.5"
}, 1000);

Try these effects:

  • fadeOut() - Gradually hides elements
  • slideToggle() - Toggles slide up/down
  • animate() - Create custom animations

jQuery HTML Methods

Manipulate HTML content and attributes with jQuery powerful methods

Syntax

Return content:

$(selector).html()

Set content:

$(selector).html(content)

Set with function:

$(selector).html(function(index, currentContent))

Parameters

content

  • What it is: The new content to set
  • What it can be: Text or HTML (can include tags)

function(index, currentContent)

  • index: Position of element (0, 1, 2...)
  • currentContent: The elements current HTML

Example

<!DOCTYPE html>
<html>
<head>
<title>jQuery html() Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
    <body style={{ textAlign: "center" }}>
    <h1 style={{ color: "green" }}>Hello World</h1>
    <h2>Hello Teens</h2>
    <button>Click</button>
    <script>
    $(document).ready(function() {
    $("button").click(function() {
    alert($("h2").html());
    });
    });
    </script>
</body>
</html>
Code Explanation:
  • When button is clicked, shows alert with HTML content of <h2>
  • Demonstrates reading content with .html()
  • Document ready ensures DOM is loaded first

Practical Usage

Setting HTML Content

// Set simple text
  $("#title").html("New Heading");
  // Set HTML content
  $("#container").html("<div class='alert'>Success!</div>");

  // Using function
  $("li").html(function(index) {
  return "Item " + (index + 1);
});

Getting HTML Content

// Get content
  var content = $("#article").html();
  // Use in condition
  if ($("#warning").html() === "") {
  $("#warning").html("<strong>Alert!</strong>");
  }
  // Log all paragraph content
  $("p").each(function() {
  console.log($(this).html());
});

jQuery DOM Traversing

Navigate and manipulate elements based on their relationships in the DOM tree

DOM Tree Structure

📁<div>
📋<ul>
<li>
<span>
<li>
<b>

Relationship Types

⬆️

Parent

Direct container element

$('ul').parent()
⬇️

Child

Direct contained element

$('div').children()
↔️

Sibling

Elements at same level

$('li').siblings()
⤴️

Ancestor

Any element above in hierarchy

$('span').parents()
⤵️

Descendant

Any element below in hierarchy

$('div').find('span')

Practical Examples

Navigation Menu

// Highlight parent menu item
  $(".menu-item.active").parent()
   .addClass("bg-[#B45309] text-white");

// Find all child links
   $(".nav-bar").find("a")
    .addClass("hover:text-[#B45309]");

Form Validation

// Find closest form
  $(".error-message").closest("form")
     .addClass("error-state");

 // Get sibling inputs
  $(".invalid").siblings("input")
      .addClass("border-red-500");

Traversal Methods

⬇️

Moving Down

.children()

Direct child elements

.find()

All matching descendants

⬆️

Moving Up

.parent()

Immediate parent element

.parents()

All ancestor elements

.closest()

First matching ancestor

↔️

Moving Sideways

.siblings()

All sibling elements

.next()

Immediate next sibling

.prev()

Immediate previous sibling

.filter()

Reduce matched elements

.first()/.last()

First/last element in set

Practical Examples

Navigation Example

// Highlight parent of active link
$(".active").parent().addClass("highlight");

// Find all links in navigation
$("#nav").find("a").addClass("text-blue-500");

// Get next sibling of current tab
$(".tab.active").next().show();

Form Example

// Find closest form ancestor
$("input").closest("form").addClass("needs-validation");

// Get all siblings of error message
$(".error").siblings().addClass("border-red-500");

// Filter visible inputs
$("input").filter(":visible").val("");

jQuery AJAX & Misc Methods

Powerful tools for asynchronous requests and utility functions

AJAX Methods

AJAX Fundamentals

The jQuery ajax() method lets you send and receive data between a web browser and server asynchronously.

Syntax:
$.ajax({name:value, name:value, ...})
Common Parameters:
typeurldatadataTypesuccesserrorcacheasync

JSON Handling

jQuery provides built-in support for handling JSON data in AJAX requests.

// Example: Fetching JSON data
$.ajax({
  url: 'https://api.example.com/users',
    method: 'GET',
    dataType: 'json',
    success: function(users) {
        users.forEach(function(user) {
        console.log(user.name);
         });
       },
    error: function(xhr, status, error) {
    console.error(error);
        }
});

Miscellaneous Methods

.each()

Iterates over jQuery objects/arrays

$("li").each(function(index, element) {
  console.log("Item " + (index + 1) + ": " 
   + $(element).text());
});

.data()

Stores/retrieves arbitrary data

$("#myDiv").data("userInfo", 
{ name: "Alice", age: 30 });
                      
// Retrieve
$("#myDiv").data("userInfo").name;

.noConflict()

Avoids $ variable conflicts

var jQ = jQuery.noConflict();
jQ("p").text("Updated using jQ");

.param()

Creates query strings

var data = { name: "Bob", city: "New York" 
};
var queryString = jQuery.param(data);
// "name=Bob&city=New%20York"

.index()

Finds element position

var listItem = $("#item3");
var index = $("li").index(listItem);
// Returns position (0-based)

Quick Reference

MethodDescription
.each()Loop through elements
.data()Get/set element data
.get()Get DOM elements as array
.index()Find element position
.toArray()Convert to JavaScript array
.removeData()Remove stored data

Object-Oriented Programming (OOPs)

Organizing code into objects containing data and behavior

Class

Blueprint for creating objects

class Vehicle {...}

Object

Instance of a class

const tesla = new Vehicle()

Encapsulation

Bundling data & methods

private #mileage

Inheritance

Child class extends parent

class Car extends Vehicle

Polymorphism

Same method, different behavior

parent.honk() vs child.honk()

Abstraction

Hiding complex logic

Simple public interfaces

OOPs in Action

// 1. CLASS (Blueprint)
class Vehicle {
// Private field (Encapsulation)
#mileage;  

constructor(make, model) {
this.make = make;
this.model = model;
this.#mileage = 0;
}

// Public method (Abstraction)
start() {
console.log(`${this.make} ${this.model} started`);
}

// Encapsulation: Controlled access
getMileage() {
return this.#mileage;
}

// Polymorphism (default)
honk() {
console.log("Beep beep!");
}
}

// 2. INHERITANCE
 class ElectricCar extends Vehicle {
   constructor(make, model, battery) {
      super(make, model);
         this.battery = battery;
   }

// 3. POLYMORPHISM
    honk() {
        console.log("Silent electric beep!");
    }

    charge() {
          console.log(`${this.make} charging...`);
             }
    }

// 4. OBJECT (Instance)
const tesla = new ElectricCar("Tesla", "Model 3", "100kWh");

// Usage:
tesla.start();       // Inherited
tesla.honk();        // Polymorphism
tesla.charge();      // Child method
tesla.getMileage();  // Encapsulated access

Key Concepts Demonstrated:

  • Class → Vehicle is the blueprint
  • Object → tesla is the concrete instance
  • Encapsulation → #mileage is private
  • Inheritance → ElectricCar extends Vehicle
  • Polymorphism → Different honk() behaviors
  • Abstraction → Simple public interfaces

Output When Executed:

Tesla Model 3 started
Silent electric beep!
Tesla charging...
0

Why Use OOPs?

Modular code organization
Easier maintenance and updates
Code reusability through inheritance
Data protection via encapsulation
Flexibility through polymorphism
Reduced complexity via abstraction