Module 12 - JQuery

Introducing jQuery

What is jQuery?

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.

Key Benefits of jQuery:

  • Simplified Syntax: Reduces the amount of code needed for complex JavaScript tasks.
  • Cross-Browser Compatibility: Handles inconsistencies between different browsers.
  • Rich Features: Includes built-in methods for DOM manipulation, animations, event handling, and AJAX.
  • Community Support: A large ecosystem of plugins and extensive documentation.

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.

Including jQuery in a Project

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>

Basic jQuery Syntax

jQuery uses a simple and consistent syntax. Here’s the basic structure:

$(selector).action();
  • $: The jQuery function (you can think of it as shorthand for “query”).
  • selector: Identifies the HTML element(s) you want to target (e.g., by id, class, or tag).
  • action(): Specifies what you want to do with the selected element(s).

For example, if you want to hide all <p> elements on a page, you can write:

$("p").hide();

Writing and Executing jQuery Code

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.



Simplified DOM Manipulation with jQuery

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.

Selecting Elements

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:

  • By Tag Name:
$("p"); // Selects all <p> elements
  • By ID:
$("#header"); // Selects the element with id="header"
  • By Class:
$(".menu"); // Selects all elements with class="menu"
  • By Attribute:
$("input[type='text']"); // Selects all text input elements

Chaining Methods: 

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.

Changing Content and Attributes

With jQuery, you can easily change the content or attributes of an element.

Modifying HTML Content: 

.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!");

Changing Form Values: 

.val(): Gets or sets the value of a form element.

$("#nameInput").val("John Doe");

Modifying Attributes: 

.attr(): Gets or sets an attribute’s value.

$("img").attr("src", "new-image.jpg");

.removeAttr(): Removes an attribute from an element.

$("img").removeAttr("alt");

Adding and Removing Elements

jQuery provides methods to dynamically add or remove elements in the DOM.

Adding New Elements: 

.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>"); 

Inserting Elements Relative to Others: 

.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>");

Removing Elements: 

.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.



Simplifying Event Handling with jQuery

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.

Adding Event Listeners

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.

Syntax:

$(selector).on(event, childSelector, data, function);
  • event: The event to listen for (e.g., click, change).
  • childSelector: (Optional) A selector for child elements to delegate the event to.
  • data: (Optional) Data to pass to the event handler.
  • function: The callback function to run when the event occurs.

Example – Adding a Click Listener:

$("#button").on("click", function() {
alert("Button clicked!");
});

Example – Adding a Change Listener:

$("input").on("change", function() {
console.log("Value changed to: " + $(this).val());
});

Shorthand Event Methods

jQuery provides shorthand methods for common events, which can make your code even more concise. These methods are wrappers around the .on() method.

Examples of Shorthand Methods:

.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!");
});

Event Delegation

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.

Example – Delegating Events:

$("#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.

Removing Event Listeners

If you need to stop an event from being triggered, you can use the .off() method to remove an event listener.

Example – Removing a 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.



Enhancing Style with jQuery

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.

Adding and Removing Classes

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.

Adding a Class:

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.

Removing a Class:

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.

Toggling a Class:

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.

Inline CSS Manipulation

jQuery allows you to directly manipulate CSS properties of elements using the .css() method.

Setting a Single Property:

Pass the property name and value as arguments to .css().

$("#title").css("color", "blue");

Setting Multiple Properties:

Pass an object containing property-value pairs.

$("#title").css({
"color": "blue",
"font-size": "24px",
"margin": "10px"
});

Getting a CSS Property:

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

Practical Example: Creating an Interactive Style Toggle

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.



Effects and Animations with jQuery

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.

Showing and Hiding Elements

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();

Example:

$("#toggleButton").click(function() {
$("#content").toggle();
});

In this example, clicking the button alternates between showing and hiding the content.

Fading Effects

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

Example:

$("#fadeButton").click(function() {
$("#content").fadeToggle(800);
});

Sliding Effects

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);

Example:

$("#menuButton").click(function() {
$("#menu").slideToggle(400);
});

Custom Animations

For more control over animations, you can use the .animate() method to animate CSS properties.

Syntax:

$(selector).animate(properties, duration, easing, callback);
  • properties: An object of CSS properties to animate (e.g., width, height, opacity).
  • duration: Time in milliseconds (or "slow", "fast").
  • easing: (Optional) Animation effect (default is "swing"; "linear" is also available).
  • callback: (Optional) Function to execute after the animation completes.

Example:

$("#box").animate({
width: "300px",
height: "200px",
opacity: 0.5
}, 1000);

This code animates the width, height, and opacity of #box over 1 second.

Combining Effects

You can chain multiple effects or animations to create complex interactions.

Example:

$("#button").click(function() {
$("#box").slideUp(500).fadeOut(500);
});

Stopping and Delaying Animations

.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.

Videos for Module 12 - JQuery

12-1: Introducing JQuery (1:12)

12-2: Getting Started With JQuery (2:32)

12-3: JQuery Selectors (5:11)

12-4: JQuery - Changing Content and Attributes (5:56)

12-5: JQuery - Adding and Removing Page Elements (5:42)

12-6: JQuery Event Listeners (1:27)

12-7: JQuery Event Listener Shorthand (1:28)

12-8: JQuery Adding and Removing Classes (3:51)

12-9: JQuery Modifying Inline CSS (1:53)

12-10: Showing and Hiding Page Elements (2:52)

12-11: JQuery Animation Effects (2:52)