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.
Before writing jQuery, you must include the library in your project (either downloaded or via CDN).
<!-- Add this inside <head> or before </body> -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
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)
// 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();
});
});
jQuery provides simple methods to interact with elements.
.html() / .text(): Get or set content.val(): Get or set form input values.css(): Change style properties.hide() / .show(): Toggle visibility.fadeIn() / .fadeOut(): Smooth opacity transition.slideUp() / .slideDown(): Height transition
// 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...");
});
Imagine you have three red boxes on the screen.
btn..box.fadeOut).Click the button below. This demonstrates how easily jQuery handles events (clicking) and effects (sliding) with minimal code.
// 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");
}
});
});
$.get() or $.post() to load data without refreshing the page.$(document).ready() to ensure the DOM is loaded.$("#p1").css("color", "red").slideUp(2000).slideDown(2000);$ (e.g., var $header = $("#header");).$, use jQuery.noConflict().querySelector).fadeIn() to show the full image..html() to change a div's content to "Hello World" when the page loads.