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

There are no videos yet this term for this Module. Check back soon!

Activities for this Module

S12 - Experimenting with JQuery

Note: Sandbox assignments are designed to be formative activities that are somewhat open-ended. To get the most value, spend some time playing around as you code.

Instructions:

In this sandbox, we'll walk through a series of activities that will give you some basic exposure to some of the ways that JQuery can make our lives significantly easier.  At the end, spend some time experimenting with JQuery code and seeing what you can do!

Before You Start: Download the template file below. It contains the HTML, CSS, and an empty <script> section where you’ll add jQuery.

S12 Template Code

Open the file, and add the following script just before the </script> tag.

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

Part 1: Change Text Color Using jQuery

 Step 1: Open index.html.

Find the <script> section at the bottom of the file. This is where your JavaScript code will go.

Step 2: Add a function to make sure the whole document is loaded before scripts are run:

Write this code inside the <script> tag:

$(document).ready(function() {
    // Code inside here will only run after the page is fully loaded
}); 

Step 3: Add a click event for the “Change Color” button:

Inside the ready function, write:

$("#changeColor").click(function() {

Explanation: This tells jQuery to wait for a click event on the button with the ID changeColor.

Step 4: Change the color of the .text element:

Right after the opening {, add:

 $(".text").css("color", "red");

Explanation: This line selects the element with the class .text and changes its CSS color to red.

Step 5: Close the event function:

Complete this block by adding:

}); 

Test It Out: Save the file, open it in your browser, and click the “Change Color” button to see the color change.

Part 2: Handle Form Input

Step 1: Add another click event for the “Greet Me!” button:

Inside the ready function, write:

 $("#greet").click(function() {

Step 2: Retrieve the user’s name:

Inside the { add:

const name = $("#nameInput").val();

Explanation: This stores the value entered in the text input field.

Step 3: Check if the input is not empty:

Below that line, add:

if (name) {
    $("#greeting").text(`Hello, ${name}!`);
} else {
    $("#greeting").text("Please enter your name.");

Step 4: Close the event function:

Complete this block by adding:

 });

Test It Out: Enter a name, click “Greet Me!” and see the personalized message appear.

Part 3: Toggle Box Animation

Step 1: Add a click event for the “Toggle Box” button:

Inside the ready function, write:

 $("#toggleBox").click(function() {

Step 2: Animate the .box element using slideToggle():

Inside the { add:

$(".box").slideToggle();

Step 3: Close the event function:

Complete this block by adding:

});

Test It Out: Click the “Toggle Box” button and watch the box slide up and down.

Part 4: Make an AJAX Request

Step 1: Add a click event for the “Load Data” button:

Inside the ready function, write:

$("#loadData").click(function() {

Step 2: Use $.ajax to fetch data:

Inside the { add:

$.ajax({
    url: "https://jsonplaceholder.typicode.com/posts/1",
    method: "GET",
    success: function(data) {
        $("#dataContainer").html(`<h3>${data.title}</h3><p>${data.body}</p>`);
        $("#dataContainer").fadeIn();
    },
    error: function() {
        alert("Failed to load data.");
    }
});

Step 3: Close the event function:

Complete this block by adding:

});

Test It Out: Click the “Load Data” button and watch as data from an external source is fetched and displayed. 

Try out a few other things using what you've learned so far in the class, along with some of the Jquery magic you've played around with in this sandbox.  When you're done, post a screenshot of your code and your page.

 

A12 - Art Pad Pixel Art

The Challenge

You will use JQuery and the starter file supplied to create a "pixel art" page that allows users to flip the color of individual pixels in the grid from white to black and back by clicking them. For a bonus challenge, try to see if you can allow users to choose a color from a palette, or cycle through a series of colors with each click.  You could also change the size of the grid or the size of each "pixel".  For an extra challenge, allow the work to be "saved" using local storage.

Download the A12 Template File Download Download the A12 Template File

Constraints / Success Criteria

  • You must use JQuery for the major functions.
  • You must use only what has been covered in this class so far.

How to Submit

Upload your HTML file.