jQuery is a fast, small, and feature-rich JavaScript library designed to simplify common scripting tasks. It helps developers write less code while doing more. With jQuery, you can easily manipulate the DOM, handle events, create animations, and perform AJAX requests—all with concise and readable syntax.
jQuery was created in 2006 and became widely popular because it made JavaScript more accessible, even for beginners. While modern browsers have caught up with many of its features, it is still a valuable tool for learning how libraries simplify JavaScript.
To use jQuery, you need to include it in your HTML file. There are two main ways to do this:
Using a CDN (Content Delivery Network):
This is the simplest and most common way to add jQuery to your project. Add the following <script> tag inside the <head> or before the closing </body> tag in your HTML file:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
This method loads jQuery directly from a trusted online source.
Downloading and Hosting Locally:
If you want to use jQuery offline, download the library from jquery.com and save it to your project directory. Then include it in your HTML file:
<script src="js/jquery-3.6.0.min.js"></script>
jQuery uses a simple and consistent syntax. Here’s the basic structure:
$(selector).action();
For example, if you want to hide all <p> elements on a page, you can write:
$("p").hide();
It’s important to ensure that the DOM is fully loaded before your jQuery code runs. Use the $(document).ready() method to wrap your code:
$(document).ready(function() {
// Your jQuery code goes here
});
Alternatively, you can use a shorthand version:
$(function() {
// Your jQuery code goes here
});
For example, to change the text of all <h1> elements once the page is ready:
$(function() {
$("h1").text("Welcome to jQuery!");
});
By the end of this section, students should understand what jQuery is, how to add it to their projects, and how to write basic jQuery code. This foundation will make it easier to explore its powerful features in the next sections.
One of the most powerful features of jQuery is its ability to simplify how you select, manipulate, and modify elements in the DOM (Document Object Model). With jQuery, tasks that would take several lines of JavaScript can often be completed with just one or two lines of code.
jQuery provides an easy way to select HTML elements using the $() function. The syntax is simple and consistent, and you can use CSS-style selectors to target elements.
Examples of Selectors:
$("p"); // Selects all <p> elements
$("#header"); // Selects the element with id="header"
$(".menu"); // Selects all elements with class="menu"
$("input[type='text']"); // Selects all text input elements
jQuery allows you to “chain” multiple actions on the same selection for efficiency:
$("#header").css("color", "blue").slideUp(1000).slideDown(1000);
In this example, the #header element is styled, hidden, and then shown again—all in one line of code.
With jQuery, you can easily change the content or attributes of an element.
.html(): Gets or sets the HTML content of an element.
$("#content").html("<strong>Updated content!</strong>");
.text(): Gets or sets the plain text content (ignores HTML tags).
$("#content").text("Plain text update!");
.val(): Gets or sets the value of a form element.
$("#nameInput").val("John Doe");
.attr(): Gets or sets an attribute’s value.
$("img").attr("src", "new-image.jpg");
.removeAttr(): Removes an attribute from an element.
$("img").removeAttr("alt");
jQuery provides methods to dynamically add or remove elements in the DOM.
.append(): Adds content to the end of an element.
$("ul").append("<li>New Item</li>");
.prepend(): Adds content to the beginning of an element.
$("ul").prepend("<li>First Item</li>");
.after(): Adds content after a selected element.
$("#title").after("<p>Subtitle goes here</p>");
.before(): Adds content before a selected element.
$("#title").before("<p>Introduction text</p>");
.remove(): Deletes an element and all its child elements.
$(".temp").remove();
.empty(): Removes all child elements without deleting the selected element itself.
$("#container").empty();
By using these jQuery methods, you can easily manipulate the content and structure of your web pages. This makes tasks like updating text, dynamically adding elements, and cleaning up the DOM much more intuitive and efficient. With a solid grasp of these basics, you’ll be ready to handle more complex interactions in your projects.
Handling events like clicks, form submissions, or mouse movements is a crucial part of creating interactive web applications. jQuery makes it simple to add, manage, and even remove event handlers with its clean, straightforward syntax.
With jQuery, you can easily attach event listeners to elements using the .on() method. The .on() method works for any event, such as click, hover, or submit.
$(selector).on(event, childSelector, data, function);
$("#button").on("click", function() {
alert("Button clicked!");
});
$("input").on("change", function() {
console.log("Value changed to: " + $(this).val());
});
jQuery provides shorthand methods for common events, which can make your code even more concise. These methods are wrappers around the .on() method.
.click(): Adds a click event listener.
$("#button").click(function() {
alert("Button clicked!");
});
.hover(): Adds both mouseenter and mouseleave events.
$(".menu-item").hover(
function() {
$(this).addClass("highlight");
},
function() {
$(this).removeClass("highlight");
}
);
.submit(): Adds a form submission event listener.
$("form").submit(function(event) {
event.preventDefault(); // Prevent form submission
alert("Form submitted!");
});
Sometimes, you need to handle events for elements that are dynamically added to the DOM. In such cases, you can use event delegation with the .on() method. This allows you to bind an event to a parent element and specify a child element selector.
$("#container").on("click", ".dynamic-item", function() {
alert("Dynamic item clicked!");
});
In this example, the click event will work for any .dynamic-item added to #container, even after the page loads.
If you need to stop an event from being triggered, you can use the .off() method to remove an event listener.
$("#button").off("click");
By using these features, jQuery simplifies how you manage events in your applications. Whether you’re listening for user interactions, delegating events for dynamic content, or cleaning up listeners, jQuery provides a clear and consistent way to handle it all. These skills will help you build interactive, user-friendly web pages with minimal effort.
jQuery makes it easy to dynamically manipulate the appearance of elements on your web page. With just a few lines of code, you can add or remove CSS classes, modify inline styles, and toggle visual effects to create interactive and visually appealing designs.
Managing CSS classes dynamically is one of the most common tasks in web development. jQuery provides simple methods to add, remove, and toggle classes on HTML elements.
Use .addClass() to apply one or more CSS classes to an element.
$("#title").addClass("highlight");
This adds the highlight class to the element with the ID title.
Use .removeClass() to remove one or more CSS classes from an element.
$("#title").removeClass("highlight");
This removes the highlight class from the element with the ID title.
Use .toggleClass() to add a class if it’s not present or remove it if it is.
$("#title").toggleClass("highlight");
This adds the highlight class if it’s missing, or removes it if it’s already applied.
Example:
$("#button").click(function() {
$("#title").toggleClass("highlight");
});
In this example, clicking the button toggles the highlight class on the title.
jQuery allows you to directly manipulate CSS properties of elements using the .css() method.
Pass the property name and value as arguments to .css().
$("#title").css("color", "blue");
Pass an object containing property-value pairs.
$("#title").css({
"color": "blue",
"font-size": "24px",
"margin": "10px"
});
To retrieve the current value of a CSS property, pass the property name as a single argument.
let color = $("#title").css("color");
console.log(color); // Outputs the current text color of #title
Here’s how you can use these methods together to build a simple feature that toggles a dark mode:
$("#darkModeToggle").click(function() {
$("body").toggleClass("dark-mode");
});
CSS:
.dark-mode {
background-color: #333;
color: #fff;
}
Clicking the button with the ID darkModeToggle will switch the page between light and dark themes.
By using these methods, you can quickly and easily update the style of your web pages in response to user interactions or application logic. Mastering these tools will help you create dynamic and responsive designs that enhance the user experience.
jQuery simplifies the process of creating effects and animations, allowing you to add interactivity and dynamic behavior to your web pages. You can hide or show elements, create fade and slide effects, or even build custom animations—all with clean, easy-to-understand code.
jQuery provides methods to control the visibility of elements.
.hide(): Hides the selected element(s).
$("#content").hide();
.show(): Shows the selected element(s).
$("#content").show();
.toggle(): Toggles visibility (shows if hidden, hides if visible).
$("#content").toggle();
$("#toggleButton").click(function() {
$("#content").toggle();
});
In this example, clicking the button alternates between showing and hiding the content.
Fading provides a smooth transition for showing or hiding elements.
.fadeIn(): Fades in an element.
$("#content").fadeIn(1000); // Fades in over 1 second
.fadeOut(): Fades out an element.
$("#content").fadeOut(1000); // Fades out over 1 second
.fadeToggle(): Toggles fading in or out.
$("#content").fadeToggle(500); // Fades in or out over 0.5 seconds
$("#fadeButton").click(function() {
$("#content").fadeToggle(800);
});
Sliding effects are great for dropdown menus or collapsible sections.
.slideUp(): Collapses an element upward.
$("#menu").slideUp(500);
.slideDown(): Expands an element downward.
$("#menu").slideDown(500);
.slideToggle(): Toggles between sliding up and down.
$("#menu").slideToggle(500);
$("#menuButton").click(function() {
$("#menu").slideToggle(400);
});
For more control over animations, you can use the .animate() method to animate CSS properties.
$(selector).animate(properties, duration, easing, callback);
$("#box").animate({
width: "300px",
height: "200px",
opacity: 0.5
}, 1000);
This code animates the width, height, and opacity of #box over 1 second.
You can chain multiple effects or animations to create complex interactions.
$("#button").click(function() {
$("#box").slideUp(500).fadeOut(500);
});
.stop(): Stops the current animation immediately.
$("#box").stop();
.delay(): Adds a delay before the next animation starts.
$("#box").fadeIn(500).delay(1000).fadeOut(500);
By mastering these effects and animations, you can create engaging, interactive web pages that respond dynamically to user actions. These tools allow you to go beyond static pages and provide a polished, professional experience.