Welcome to the comprehensive guide on jQuery! jQuery is a fast, small, and feature-rich JavaScript library that simplifies tasks like HTML document traversal and manipulation, event handling, animation, and Ajax interactions for rapid web development. This guide is designed to take you from the basics of jQuery to more advanced topics, complete with code examples, detailed explanations, exercises, and multiple-choice questions to test your understanding.
1. Introduction to jQuery
What is jQuery?
jQuery is a fast, lightweight, and feature-rich JavaScript library. It was created by John Resig and released in January 2006. jQuery simplifies tasks such as HTML document traversal and manipulation, event handling, animation, and Ajax interactions, making it easier to develop highly interactive web applications.
Why Use jQuery?
- Simplified Syntax: jQuery provides an easy-to-use API that works across a multitude of browsers, abstracting away complexities.
- Cross-Browser Compatibility: Handles inconsistencies between different browsers, ensuring your code works uniformly.
- Rich Ecosystem: A vast collection of plugins extends jQuery’s functionality, enabling rapid feature development.
- Efficient DOM Manipulation: Streamlines the process of selecting and manipulating DOM elements.
- AJAX Support: Simplifies asynchronous HTTP requests for dynamic content loading without page refreshes.
Including jQuery in Your Project
You can include jQuery in your project either by downloading it or by linking to a Content Delivery Network (CDN).
1. Using a CDN
Linking to a CDN is recommended for better performance and caching benefits.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery CDN Example</title>
<!– jQuery CDN –>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
</head>
<body>
<!– Your content here –>
</body>
</html>
2. Downloading jQuery
Alternatively, you can download jQuery and host it locally.
- Download jQuery from the official website.
- Save the file (e.g., jquery-3.6.0.min.js) in your project’s directory.
- Include it in your HTML:
<script src=”js/jquery-3.6.0.min.js”></script>
Note: Always ensure you are using the latest stable version of jQuery for security and performance improvements.
2. jQuery Syntax and Structure
Understanding the basic syntax and structure of jQuery is essential for effective usage.
Basic Syntax
The basic syntax of jQuery involves selecting elements and performing actions on them.
$(selector).action();
- $: The jQuery function.
- selector: A string containing a CSS selector to identify the elements.
- action(): A jQuery method to perform on the selected elements.
Example: Changing Text of a Paragraph
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery Basic Syntax</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script>
$(document).ready(function(){
$(“p”).text(“Hello, jQuery!”);
});
</script>
</head>
<body>
<p>This text will be changed.</p>
</body>
</html>
Explanation:
- $(document).ready(function(){ … });: Ensures the DOM is fully loaded before executing the jQuery code.
- $(“p”): Selects all <p> elements.
- .text(“Hello, jQuery!”);: Changes the text content of the selected paragraphs.
Document Ready Function
The Document Ready function ensures that the jQuery code runs only after the DOM is fully loaded, preventing errors from attempting to manipulate elements that aren’t yet present.
Syntax:
$(document).ready(function(){
// Your jQuery code here
});
Shorthand Syntax:
$(function(){
// Your jQuery code here
});
Example: Shorthand Document Ready
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery Document Ready</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script>
$(function(){
$(“#welcome”).hide().fadeIn(2000);
});
</script>
</head>
<body>
<h1 id=”welcome”>Welcome to jQuery!</h1>
</body>
</html>
Explanation:
- $(“#welcome”): Selects the element with the ID welcome.
- .hide().fadeIn(2000);: Initially hides the element and then fades it in over 2 seconds.
3. Selectors
jQuery selectors allow you to select and manipulate HTML elements with ease. They are based on CSS selectors but offer additional flexibility.
Basic Selectors
1. Element Selector
Selects all elements of a given type.
$(“p”).hide(); // Hides all <p> elements
Example:
<p>This is a paragraph.</p>
<p>Another paragraph.</p>
<script>
$(“p”).hide(); // Hides both paragraphs
</script>
2. ID Selector
Selects an element with a specific ID.
$(“#header”).css(“background-color”, “blue”); // Changes background color of element with ID ‘header’
Example:
<div id=”header”>Header Section</div>
<script>
$(“#header”).css(“background-color”, “blue”); // Sets background to blue
</script>
3. Class Selector
Selects all elements with a specific class.
$(“.menu-item”).addClass(“active”); // Adds ‘active’ class to all elements with class ‘menu-item’
Example:
<ul>
<li class=”menu-item”>Home</li>
<li class=”menu-item”>About</li>
<li class=”menu-item”>Contact</li>
</ul>
<script>
$(“.menu-item”).addClass(“active”); // Adds ‘active’ class to all menu items
</script>
Attribute Selectors
Selects elements based on their attributes and attribute values.
1. Attribute Presence Selector
Selects elements that have a specific attribute, regardless of its value.
$(“input[disabled]”).css(“background-color”, “#ccc”); // Styles all disabled input fields
2. Attribute Value Selector
Selects elements with a specific attribute value.
$(“a[href=’https://www.example.com’]”).css(“color”, “red”); // Changes color of specific link
3. Attribute Contains Selector
Selects elements with an attribute value containing a specific substring.
$(“a[href*=’example’]”).css(“font-weight”, “bold”); // Boldens links containing ‘example’ in href
Example:
<input type=”text” disabled>
<input type=”password”>
<a href=”https://www.example.com”>Example</a>
<a href=”https://www.test.com”>Test</a>
<script>
$(“input[disabled]”).css(“background-color”, “#ccc”);
$(“a[href*=’example’]”).css(“font-weight”, “bold”);
</script>
Pseudo-Selectors
Pseudo-selectors target elements in specific states or positions.
1.
Selector
Selects the first element among a group.
$(“li:first”).css(“color”, “green”); // Changes color of the first <li> element
2.
Selector
Selects the last element among a group.
$(“li:last”).css(“color”, “blue”); // Changes color of the last <li> element
3.
and
Selectors
Selects elements based on their index.
$(“tr:even”).css(“background-color”, “#f2f2f2”); // Styles even table rows
$(“tr:odd”).css(“background-color”, “#ffffff”); // Styles odd table rows
Example:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
<script>
$(“li:first”).css(“color”, “green”);
$(“li:last”).css(“color”, “blue”);
$(“li:even”).css(“background-color”, “#f2f2f2”);
$(“li:odd”).css(“background-color”, “#ffffff”);
</script>
Traversal Selectors
jQuery provides methods to traverse and navigate through the DOM tree.
1. .parent()
Selects the parent of each element in the set.
$(“.child”).parent().css(“border”, “1px solid #000”); // Adds border to parent elements
2. .children()
Selects all direct children of each element in the set.
$(“ul”).children(“li”).css(“padding”, “10px”); // Adds padding to <li> children
3. .siblings()
Selects all siblings of each element in the set.
$(“#current”).siblings().css(“color”, “gray”); // Changes color of sibling elements
4. .find()
Selects descendant elements of each element in the set.
$(“div”).find(“p”).css(“font-size”, “16px”); // Changes font size of all <p> within <div>
Example:
<div class=”container”>
<ul>
<li class=”child”>List Item 1</li>
<li class=”child”>List Item 2</li>
</ul>
</div>
<script>
$(“.child”).parent().css(“border”, “1px solid #000”);
$(“ul”).children(“li”).css(“padding”, “10px”);
$(“.child:first”).siblings().css(“color”, “gray”);
$(“.container”).find(“li”).css(“background-color”, “#ddd”);
</script>
4. Events
jQuery simplifies event handling, allowing you to respond to user interactions seamlessly.
Event Handling
Handling events such as clicks, hovers, form submissions, and more is straightforward with jQuery.
1. .click()
Binds a click event to selected elements.
$(“#myButton”).click(function(){
alert(“Button clicked!”);
});
Example:
<button id=”myButton”>Click Me</button>
<script>
$(“#myButton”).click(function(){
alert(“Button clicked!”);
});
</script>
2. .hover()
Binds handlers for mouseenter and mouseleave events.
$(“.hover-item”).hover(
function(){
$(this).css(“background-color”, “#f1c40f”);
},
function(){
$(this).css(“background-color”, “#ecf0f1”);
}
);
Example:
<div class=”hover-item” style=”width:100px; height:100px; background-color:#ecf0f1; margin:10px;”>
Hover over me
</div>
<script>
$(“.hover-item”).hover(
function(){
$(this).css(“background-color”, “#f1c40f”);
},
function(){
$(this).css(“background-color”, “#ecf0f1”);
}
);
</script>
3. .on()
Attaches event handlers for one or more events to selected elements.
$(“button”).on(“click”, function(){
$(this).toggleClass(“active”);
});
Example:
<button class=”toggle-btn”>Toggle Active</button>
<script>
$(“button.toggle-btn”).on(“click”, function(){
$(this).toggleClass(“active”);
});
</script>
Event Methods
jQuery provides various methods to manage events beyond just binding.
1. .preventDefault()
Prevents the default action of an event (e.g., preventing a form from submitting).
$(“a.no-link”).click(function(event){
event.preventDefault();
alert(“Default action prevented.”);
});
2. .stopPropagation()
Stops the event from bubbling up the DOM tree.
$(“.child”).click(function(event){
event.stopPropagation();
alert(“Child clicked!”);
});
Example:
<div class=”parent” style=”padding:50px; background-color:#bdc3c7;”>
Parent Div
<div class=”child” style=”padding:20px; background-color:#ecf0f1;”>
Child Div
</div>
</div>
<script>
$(“.parent”).click(function(){
alert(“Parent clicked!”);
});
$(“.child”).click(function(event){
event.stopPropagation();
alert(“Child clicked!”);
});
</script>
Explanation:
- Clicking on the child div will only trigger the child’s click event, not the parent’s, due to .stopPropagation().
Event Delegation
Event delegation involves binding an event to a parent element to manage events for dynamically added child elements.
$(“#parent”).on(“click”, “.child”, function(){
$(this).css(“color”, “red”);
});
Example:
<button id=”addButton”>Add Child</button>
<div id=”parent”>
<div class=”child”>Child 1</div>
</div>
<script>
let count = 2;
$(“#addButton”).click(function(){
$(“#parent”).append(`<div class=”child”>Child ${count}</div>`);
count++;
});
$(“#parent”).on(“click”, “.child”, function(){
$(this).css(“color”, “red”);
});
</script>
Explanation:
- New .child elements added dynamically will still have the click event bound to them via event delegation.
5. DOM Manipulation
jQuery simplifies the process of interacting with the DOM, allowing for dynamic changes to the webpage.
Changing Content
1. .text()
Gets or sets the text content of selected elements.
// Get text
let paraText = $(“p”).text();
// Set text
$(“p”).text(“New paragraph text.”);
2. .html()
Gets or sets the HTML content of selected elements.
// Get HTML
let divContent = $(“#myDiv”).html();
// Set HTML
$(“#myDiv”).html(“<strong>Bold Text</strong>”);
Example:
<p id=”paragraph”>Original Text</p>
<div id=”myDiv”>Original <em>HTML</em></div>
<script>
$(“#paragraph”).text(“Updated Text”);
$(“#myDiv”).html(“<strong>Updated HTML</strong>”);
</script>
Changing Attributes
1. .attr()
Gets or sets attributes of selected elements.
// Get attribute
let href = $(“a”).attr(“href”);
// Set attribute
$(“a”).attr(“href”, “https://www.newsite.com”);
2. .removeAttr()
Removes an attribute from selected elements.
$(“img”).removeAttr(“alt”);
Example:
<img id=”myImage” src=”image.jpg” alt=”Original Alt”>
<a id=”myLink” href=”https://www.example.com”>Visit Example</a>
<script>
// Change image alt text
$(“#myImage”).attr(“alt”, “Updated Alt Text”);
// Change link href
$(“#myLink”).attr(“href”, “https://www.newsite.com”);
</script>
Adding and Removing Elements
1. .append()
Inserts content at the end of selected elements.
$(“#list”).append(“<li>New Item</li>”);
2. .prepend()
Inserts content at the beginning of selected elements.
$(“#list”).prepend(“<li>First Item</li>”);
3. .before() and .after()
Inserts content before or after selected elements.
$(“h2”).before(“<hr>”);
$(“h2”).after(“<hr>”);
4. .remove()
Removes selected elements from the DOM.
$(“.remove-me”).remove();
5. .empty()
Removes all child elements and content from selected elements.
$(“#container”).empty();
Example:
<ul id=”list”>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button id=”addItem”>Add Item</button>
<button id=”removeItem”>Remove Item</button>
<script>
$(“#addItem”).click(function(){
$(“#list”).append(“<li>New Item</li>”);
});
$(“#removeItem”).click(function(){
$(“#list li:last”).remove();
});
</script>
Explanation:
- Clicking “Add Item” appends a new <li> to the list.
- Clicking “Remove Item” removes the last <li> from the list.
Example: Interactive Content Manipulation
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery DOM Manipulation</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#content {
padding: 20px;
border: 1px solid #bdc3c7;
margin-bottom: 20px;
}
.highlight {
background-color: #f1c40f;
}
</style>
</head>
<body>
<div id=”content”>
<h2>Original Content</h2>
<p>This is the original paragraph.</p>
</div>
<button id=”changeText”>Change Text</button>
<button id=”addElement”>Add Element</button>
<button id=”removeElement”>Remove Element</button>
<button id=”toggleHighlight”>Toggle Highlight</button>
<script>
$(“#changeText”).click(function(){
$(“#content p”).text(“The paragraph text has been changed!”);
});
$(“#addElement”).click(function(){
$(“#content”).append(“<p>New paragraph added.</p>”);
});
$(“#removeElement”).click(function(){
$(“#content p:last”).remove();
});
$(“#toggleHighlight”).click(function(){
$(“#content”).toggleClass(“highlight”);
});
</script>
</body>
</html>
Explanation:
- Change Text: Updates the text of the existing paragraph.
- Add Element: Appends a new paragraph to the content div.
- Remove Element: Removes the last paragraph within the content div.
- Toggle Highlight: Toggles a CSS class that changes the background color of the content div.
6. Effects and Animations
jQuery provides a suite of methods to create visual effects and animations, enhancing user experience.
Show/Hide Elements
1. .show()
Displays hidden elements.
$(“#myDiv”).show();
2. .hide()
Hides visible elements.
$(“#myDiv”).hide();
3. .toggle()
Toggles the visibility of elements.
$(“#myDiv”).toggle();
Example:
<button id=”toggleButton”>Toggle Div</button>
<div id=”myDiv” style=”width:100px; height:100px; background-color:#3498db; display:none;”></div>
<script>
$(“#toggleButton”).click(function(){
$(“#myDiv”).toggle();
});
</script>
Explanation:
- Clicking the “Toggle Div” button shows or hides the blue div.
Fading Elements
1. .fadeIn()
Gradually changes the opacity of elements to 1 (fully visible).
$(“#myDiv”).fadeIn(1000); // Fades in over 1 second
2. .fadeOut()
Gradually changes the opacity of elements to 0 (fully hidden).
$(“#myDiv”).fadeOut(1000); // Fades out over 1 second
3. .fadeToggle()
Toggles between fading in and fading out elements.
$(“#myDiv”).fadeToggle(1000); // Toggles fade over 1 second
Example:
<button id=”fadeButton”>Fade Toggle</button>
<div id=”myDiv” style=”width:100px; height:100px; background-color:#e74c3c;”></div>
<script>
$(“#fadeButton”).click(function(){
$(“#myDiv”).fadeToggle(1000);
});
</script>
Explanation:
- Clicking the “Fade Toggle” button fades the red div in or out over 1 second.
Sliding Elements
1. .slideDown()
Slides elements down to make them visible.
$(“#myDiv”).slideDown(1000); // Slides down over 1 second
2. .slideUp()
Slides elements up to hide them.
$(“#myDiv”).slideUp(1000); // Slides up over 1 second
3. .slideToggle()
Toggles between sliding elements up and down.
$(“#myDiv”).slideToggle(1000); // Toggles slide over 1 second
Example:
<button id=”slideButton”>Slide Toggle</button>
<div id=”myDiv” style=”width:100px; height:100px; background-color:#2ecc71; display:none;”></div>
<script>
$(“#slideButton”).click(function(){
$(“#myDiv”).slideToggle(1000);
});
</script>
Explanation:
- Clicking the “Slide Toggle” button slides the green div down or up over 1 second.
Custom Animations
jQuery’s .animate() method allows you to create custom animations by changing CSS properties over time.
Syntax:
$(selector).animate({ properties }, duration, easing, callback);
- properties: An object of CSS properties to animate.
- duration: Time in milliseconds or predefined strings like “slow” or “fast”.
- easing: Type of easing (e.g., “linear”, “swing”).
- callback: Function to execute after the animation completes.
Example:
<button id=”animateButton”>Animate Div</button>
<div id=”myDiv” style=”width:100px; height:100px; background-color:#9b59b6;”></div>
<script>
$(“#animateButton”).click(function(){
$(“#myDiv”).animate({
width: “200px”,
height: “200px”,
opacity: 0.5
}, 2000, “swing”, function(){
alert(“Animation complete!”);
});
});
</script>
Explanation:
- Clicking the “Animate Div” button enlarges the purple div to 200px by 200px, reduces opacity to 0.5 over 2 seconds.
- After the animation completes, an alert is shown.
Example: Combining Effects
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery Effects Example</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#box {
width: 150px;
height: 150px;
background-color: #e67e22;
margin: 50px auto;
display: none;
}
button {
display: block;
margin: 10px auto;
padding: 10px 20px;
}
</style>
</head>
<body>
<button id=”showButton”>Show Box</button>
<button id=”hideButton”>Hide Box</button>
<button id=”animateButton”>Animate Box</button>
<div id=”box”></div>
<script>
$(“#showButton”).click(function(){
$(“#box”).fadeIn(1000);
});
$(“#hideButton”).click(function(){
$(“#box”).fadeOut(1000);
});
$(“#animateButton”).click(function(){
$(“#box”).animate({
width: “250px”,
height: “250px”,
backgroundColor: “#1abc9c”
}, 2000);
});
</script>
</body>
</html>
Explanation:
- Show Box: Fades in the orange box over 1 second.
- Hide Box: Fades out the box over 1 second.
- Animate Box: Enlarges the box and changes its background color to teal over 2 seconds.
Note: Animating colors with .animate() requires the jQuery UI library or additional plugins, as the basic jQuery .animate() does not support color animations by default.
7. AJAX with jQuery
Asynchronous JavaScript and XML (AJAX) allows web pages to communicate with servers without reloading the page. jQuery simplifies AJAX operations, making it easier to fetch and send data.
Basic AJAX Request
Using the .ajax() method to perform an AJAX request.
Syntax:
$.ajax({
url: “url”,
type: “GET or POST”,
data: { key: “value” },
success: function(response){
// Handle success
},
error: function(xhr, status, error){
// Handle error
}
});
Example: Fetching Data from an API
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery AJAX Example</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
</head>
<body>
<button id=”fetchData”>Fetch Data</button>
<div id=”result”></div>
<script>
$(“#fetchData”).click(function(){
$.ajax({
url: “https://api.agify.io/?name=michael”,
type: “GET”,
success: function(response){
$(“#result”).html(`<p>Name: ${response.name}</p><p>Predicted Age: ${response.age}</p>`);
},
error: function(){
$(“#result”).html(“<p>An error occurred.</p>”);
}
});
});
</script>
</body>
</html>
Explanation:
- Clicking the “Fetch Data” button sends a GET request to the Agify API to predict the age based on the name “Michael”.
- On success, it displays the name and predicted age.
- On error, it displays an error message.
$.get and $.post Methods
jQuery provides shorthand methods for AJAX GET and POST requests.
1. $.get()
Performs a GET request.
Syntax:
$.get(url, data, success);
Example:
$.get(“https://api.agify.io/”, { name: “jessica” }, function(response){
console.log(response);
});
2. $.post()
Performs a POST request.
Syntax:
$.post(url, data, success);
Example:
$.post(“https://example.com/submit”, { username: “john”, password: “doe123” }, function(response){
console.log(response);
});
Note: POST requests typically involve sending data to the server, such as form submissions.
Handling Responses
jQuery allows handling different response data types like JSON, XML, HTML, and text.
1. JSON Response
$.ajax({
url: “https://api.agify.io/?name=michael”,
dataType: “json”,
success: function(data){
console.log(data.name); // michael
console.log(data.age); // predicted age
}
});
2. XML Response
$.ajax({
url: “data.xml”,
dataType: “xml”,
success: function(xml){
$(xml).find(“item”).each(function(){
let name = $(this).find(“name”).text();
console.log(name);
});
}
});
Example: AJAX-Based Content Loading
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery AJAX Content Loading</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#content {
padding: 20px;
border: 1px solid #bdc3c7;
margin-top: 20px;
}
</style>
</head>
<body>
<button id=”loadContent”>Load Content</button>
<div id=”content”>Content will be loaded here.</div>
<script>
$(“#loadContent”).click(function(){
$.ajax({
url: “https://jsonplaceholder.typicode.com/posts/1”,
type: “GET”,
dataType: “json”,
success: function(data){
$(“#content”).html(`<h3>${data.title}</h3><p>${data.body}</p>`);
},
error: function(){
$(“#content”).html(“<p>An error occurred while loading content.</p>”);
}
});
});
</script>
</body>
</html>
Explanation:
- Clicking the “Load Content” button sends a GET request to the JSONPlaceholder API.
- On success, it displays the title and body of the post.
- On error, it shows an error message.
8. Plugins and Extensibility
jQuery’s plugin architecture allows developers to extend its functionality easily. There is a vast ecosystem of plugins available for various purposes, from form validation to image sliders.
Using jQuery Plugins
To use a jQuery plugin, follow these general steps:
- Include jQuery: Ensure jQuery is included before the plugin script.
- Include Plugin Script: Add the plugin’s JavaScript file.
- Initialize the Plugin: Use jQuery to initialize the plugin on selected elements.
Example: Using the jQuery UI Datepicker Plugin
- Include jQuery and jQuery UI:
<head>
<meta charset=”UTF-8″>
<title>jQuery Plugin Example</title>
<link rel=”stylesheet” href=”https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css”>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script src=”https://code.jquery.com/ui/1.13.2/jquery-ui.min.js”></script>
</head>
- HTML Input Element:
<body>
<p>Date: <input type=”text” id=”datepicker”></p>
</body>
- Initialize Datepicker:
<script>
$(function(){
$(“#datepicker”).datepicker();
});
</script>
Explanation:
- The jQuery UI library provides the datepicker plugin.
- After including the necessary scripts and styles, the plugin is initialized on the input with ID datepicker.
Creating Your Own Plugin
Creating custom jQuery plugins allows you to encapsulate functionality for reuse and better organization.
Basic Plugin Structure:
(function($){
$.fn.myPlugin = function(options){
// Default settings
const settings = $.extend({
color: “blue”,
backgroundColor: “yellow”
}, options );
// Plugin functionality
return this.each(function(){
$(this).css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
});
};
})(jQuery);
Using the Custom Plugin:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery Custom Plugin</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script>
(function($){
$.fn.myPlugin = function(options){
const settings = $.extend({
color: “blue”,
backgroundColor: “yellow”
}, options );
return this.each(function(){
$(this).css({
color: settings.color,
backgroundColor: settings.backgroundColor
});
});
};
})(jQuery);
$(document).ready(function(){
$(“p”).myPlugin({
color: “white”,
backgroundColor: “green”
});
});
</script>
</head>
<body>
<p>This paragraph is styled using a custom jQuery plugin.</p>
</body>
</html>
Explanation:
- Plugin Definition: The plugin myPlugin is defined within an immediately invoked function expression (IIFE) to avoid polluting the global namespace.
- Default Settings: $.extend() merges user-provided options with default settings.
- Plugin Functionality: Applies CSS styles to each selected element.
- Usage: The plugin is invoked on all <p> elements with custom color settings.
Popular jQuery Plugins
- jQuery UI: Provides interactions, widgets, and effects.
- Slick Carousel: A responsive carousel/slider plugin.
- Select2: Enhances select boxes with search and multi-select capabilities.
- DataTables: Adds advanced interaction controls to HTML tables.
- Validate: Simplifies client-side form validation.
Example: Using Slick Carousel
- Include jQuery and Slick Carousel:
<head>
<meta charset=”UTF-8″>
<title>Slick Carousel Example</title>
<link rel=”stylesheet” href=”https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css”>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script src=”https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js”></script>
</head>
- HTML Markup:
<body>
<div class=”carousel”>
<div><img src=”images/slide1.jpg” alt=”Slide 1″></div>
<div><img src=”images/slide2.jpg” alt=”Slide 2″></div>
<div><img src=”images/slide3.jpg” alt=”Slide 3″></div>
</div>
</body>
- Initialize Slick Carousel:
<script>
$(document).ready(function(){
$(‘.carousel’).slick({
dots: true,
infinite: true,
speed: 500,
slidesToShow: 1,
adaptiveHeight: true
});
});
</script>
Explanation:
- Initialization: The .slick() method initializes the carousel with specified options like dots, infinite looping, and slide speed.
- Carousel Structure: Each slide is wrapped within a <div> inside the .carousel container.
9. Best Practices
Following best practices ensures that your jQuery code is efficient, maintainable, and scalable.
Performance Optimization
Minimize DOM Access: Cache selectors to avoid repeated DOM queries.
// Inefficient
$(“p”).hide();
$(“p”).css(“color”, “red”);
// Efficient
const $paragraphs = $(“p”);
$paragraphs.hide();
$paragraphs.css(“color”, “red”);
Use Specific Selectors: More specific selectors are faster and reduce the chance of unintended matches.
// Less specific
$(“div p”).css(“color”, “blue”);
// More specific
$(“#mainContent p”).css(“color”, “blue”);
- Limit Use of Complex Selectors: Complex selectors can slow down performance, especially in large documents.
- Delegate Events Appropriately: Use event delegation to manage events efficiently, especially for dynamic content.
Code Organization
- Separate Concerns: Keep HTML, CSS, and JavaScript in separate files.
- Modular Code: Break down your code into reusable functions and modules.
Consistent Naming Conventions: Use meaningful and consistent names for variables, functions, and selectors.
// Good naming
const $submitButton = $(“#submitButton”);
$submitButton.click(handleSubmit);
function handleSubmit() {
// Submission logic
}
Avoiding Conflicts
Use jQuery in No-Conflict Mode: If you’re using other libraries that use the $ symbol, avoid conflicts by using jQuery.noConflict().
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j(“p”).text(“No conflict mode!”);
});
Encapsulate Code: Use IIFEs to contain your jQuery code and prevent global namespace pollution.
(function($){
$(document).ready(function(){
$(“p”).css(“color”, “purple”);
});
})(jQuery);
Accessibility Considerations
- Ensure Interactive Elements Are Accessible: Make sure buttons and links are keyboard navigable.
- Provide Feedback: Use visual cues like changing styles on interactions.
- Use ARIA Attributes Wisely: Enhance accessibility without overcomplicating the DOM.
Example: Organized and Efficient jQuery Code
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Best Practices Example</title>
<link rel=”stylesheet” href=”styles.css”>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<script src=”scripts.js” defer></script>
</head>
<body>
<header>
<h1>My Website</h1>
<nav>
<ul>
<li><a href=”#home” class=”nav-link”>Home</a></li>
<li><a href=”#about” class=”nav-link”>About</a></li>
<li><a href=”#contact” class=”nav-link”>Contact</a></li>
</ul>
</nav>
</header>
<main id=”home”>
<h2>Welcome</h2>
<p>Welcome to my website.</p>
</main>
<footer>
<p>© 2024 My Website</p>
</footer>
</body>
</html>
// scripts.js
(function($){
$(document).ready(function(){
const $navLinks = $(“.nav-link”);
$navLinks.click(function(event){
event.preventDefault();
const target = $(this).attr(“href”);
$(“html, body”).animate({
scrollTop: $(target).offset().top
}, 1000);
});
});
})(jQuery);
Explanation:
- IIFE: Encapsulates the jQuery code to avoid global namespace pollution.
- Caching Selectors: Stores the navigation links in $navLinks to prevent repeated DOM queries.
- Event Handling: Smoothly scrolls to the target section when a navigation link is clicked.
- Prevent Default Behavior: Stops the default anchor behavior to implement custom scrolling.
10. Projects and Exercises
Applying what you’ve learned through projects and exercises is essential for mastering jQuery. Below are several hands-on activities to reinforce your understanding.
Exercise 1: Interactive Navigation Menu
Objective: Create a navigation menu where clicking on a menu item highlights it and displays corresponding content without reloading the page.
Features:
- Navigation links to different sections.
- Highlight the active menu item.
- Display content based on the selected menu item.
Solution Outline:
- HTML Structure:
- Create a navigation bar with menu items.
- Create content sections corresponding to each menu item.
- CSS Styling:
- Style the navigation bar.
- Highlight active menu items.
- Hide all content sections initially except the first.
- jQuery Functionality:
- Handle click events on menu items.
- Highlight the selected menu item.
- Show the corresponding content section while hiding others.
Sample Code:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Interactive Navigation Menu</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
body {
font-family: Arial, sans-serif;
}
.navbar {
background-color: #34495e;
overflow: hidden;
}
.navbar a {
float: left;
display: block;
color: #ecf0f1;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
.navbar a.active {
background-color: #2ecc71;
color: white;
}
.content-section {
display: none;
padding: 20px;
border: 1px solid #bdc3c7;
margin-top: 10px;
}
.content-section.active {
display: block;
}
</style>
</head>
<body>
<div class=”navbar”>
<a href=”#home” class=”active”>Home</a>
<a href=”#about”>About</a>
<a href=”#services”>Services</a>
<a href=”#contact”>Contact</a>
</div>
<div id=”home” class=”content-section active”>
<h2>Home</h2>
<p>Welcome to our homepage!</p>
</div>
<div id=”about” class=”content-section”>
<h2>About</h2>
<p>Learn more about us.</p>
</div>
<div id=”services” class=”content-section”>
<h2>Services</h2>
<p>Discover our services.</p>
</div>
<div id=”contact” class=”content-section”>
<h2>Contact</h2>
<p>Get in touch with us.</p>
</div>
<script>
$(document).ready(function(){
$(“.navbar a”).click(function(event){
event.preventDefault();
// Remove ‘active’ class from all menu items
$(“.navbar a”).removeClass(“active”);
// Add ‘active’ class to the clicked menu item
$(this).addClass(“active”);
// Hide all content sections
$(“.content-section”).removeClass(“active”);
// Show the corresponding content section
const target = $(this).attr(“href”);
$(target).addClass(“active”);
});
});
</script>
</body>
</html>
Explanation:
- HTML: Defines a navigation bar with links to different sections and corresponding content sections.
- CSS: Styles the navigation bar, active menu items, and content sections.
- jQuery:
- Binds click events to navigation links.
- Prevents the default anchor behavior.
- Toggles the active class on menu items and content sections to show/hide content.
Exercise 2: Dynamic Content Loading
Objective: Create a webpage that loads additional content dynamically when a “Load More” button is clicked, without refreshing the page.
Features:
- Initial set of content displayed.
- “Load More” button fetches additional content via AJAX.
- Append new content to the existing content area.
Solution Outline:
- HTML Structure:
- Content container displaying initial items.
- “Load More” button.
- Backend Setup:
- Simulate an API endpoint that returns additional content (for testing, use a public API or mock data).
- jQuery Functionality:
- Handle click event on the “Load More” button.
- Perform an AJAX request to fetch new content.
- Append the fetched content to the content container.
- Optionally, disable the button when no more content is available.
Sample Code:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Dynamic Content Loading</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#content {
max-width: 600px;
margin: auto;
padding: 20px;
}
.post {
border-bottom: 1px solid #bdc3c7;
padding: 10px 0;
}
#loadMore {
display: block;
margin: 20px auto;
padding: 10px 20px;
background-color: #2980b9;
color: white;
border: none;
cursor: pointer;
}
#loadMore:disabled {
background-color: #95a5a6;
cursor: not-allowed;
}
</style>
</head>
<body>
<div id=”content”>
<div class=”post”>
<h3>Post 1</h3>
<p>This is the first post.</p>
</div>
<div class=”post”>
<h3>Post 2</h3>
<p>This is the second post.</p>
</div>
<div class=”post”>
<h3>Post 3</h3>
<p>This is the third post.</p>
</div>
</div>
<button id=”loadMore”>Load More</button>
<script>
let page = 1;
const limit = 3; // Number of posts per page
$(“#loadMore”).click(function(){
page++;
$.ajax({
url: `https://jsonplaceholder.typicode.com/posts?_page=${page}&_limit=${limit}`,
type: “GET”,
success: function(data){
if(data.length > 0){
data.forEach(function(post){
$(“#content”).append(`
<div class=”post”>
<h3>${post.title}</h3>
<p>${post.body}</p>
</div>
`);
});
} else {
$(“#loadMore”).prop(“disabled”, true).text(“No More Posts”);
}
},
error: function(){
alert(“An error occurred while loading more posts.”);
}
});
});
</script>
</body>
</html>
Explanation:
- HTML: Displays initial posts and a “Load More” button.
- CSS: Styles the content area and button.
- jQuery:
- Keeps track of the current page and limit of posts per page.
- On clicking “Load More,” increments the page number and fetches new posts from the JSONPlaceholder API.
- Appends the new posts to the content container.
- Disables the button and changes its text when no more posts are available.
Exercise 3: Form Validation
Objective: Implement client-side form validation using jQuery to ensure users provide valid input before submission.
Features:
- Validate required fields.
- Check for valid email format.
- Provide real-time feedback to users.
Solution Outline:
- HTML Structure:
- Create a form with fields like name, email, and password.
- Include placeholders and labels for accessibility.
- CSS Styling:
- Style the form and validation messages.
- jQuery Functionality:
- Handle form submission event.
- Validate each field based on criteria.
- Display error messages next to invalid fields.
- Prevent form submission if validation fails.
Sample Code:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>Form Validation with jQuery</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
.form-group {
margin-bottom: 15px;
position: relative;
}
.form-group label {
display: block;
}
.form-group input {
width: 100%;
padding: 8px;
box-sizing: border-box;
}
.error-message {
color: red;
font-size: 0.9em;
position: absolute;
top: 100%;
left: 0;
}
.success {
border-color: green;
}
.error {
border-color: red;
}
#submitBtn {
padding: 10px 20px;
background-color: #27ae60;
color: white;
border: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Registration Form</h2>
<form id=”registrationForm” action=”#” method=”POST”>
<div class=”form-group”>
<label for=”name”>Name<span style=”color:red;”>*</span>:</label>
<input type=”text” id=”name” name=”name” placeholder=”Your name”>
<div class=”error-message”></div>
</div>
<div class=”form-group”>
<label for=”email”>Email<span style=”color:red;”>*</span>:</label>
<input type=”email” id=”email” name=”email” placeholder=”you@example.com”>
<div class=”error-message”></div>
</div>
<div class=”form-group”>
<label for=”password”>Password<span style=”color:red;”>*</span>:</label>
<input type=”password” id=”password” name=”password” placeholder=”Enter password”>
<div class=”error-message”></div>
</div>
<button type=”submit” id=”submitBtn”>Register</button>
</form>
<script>
$(document).ready(function(){
$(“#registrationForm”).submit(function(event){
event.preventDefault();
let isValid = true;
// Clear previous error messages
$(“.error-message”).text(“”);
$(“input”).removeClass(“error success”);
// Validate Name
const name = $(“#name”).val().trim();
if(name === “”){
isValid = false;
$(“#name”).addClass(“error”);
$(“#name”).next(“.error-message”).text(“Name is required.”);
} else {
$(“#name”).addClass(“success”);
}
// Validate Email
const email = $(“#email”).val().trim();
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if(email === “”){
isValid = false;
$(“#email”).addClass(“error”);
$(“#email”).next(“.error-message”).text(“Email is required.”);
} else if(!emailRegex.test(email)){
isValid = false;
$(“#email”).addClass(“error”);
$(“#email”).next(“.error-message”).text(“Enter a valid email.”);
} else {
$(“#email”).addClass(“success”);
}
// Validate Password
const password = $(“#password”).val().trim();
if(password === “”){
isValid = false;
$(“#password”).addClass(“error”);
$(“#password”).next(“.error-message”).text(“Password is required.”);
} else if(password.length < 6){
isValid = false;
$(“#password”).addClass(“error”);
$(“#password”).next(“.error-message”).text(“Password must be at least 6 characters.”);
} else {
$(“#password”).addClass(“success”);
}
if(isValid){
alert(“Form submitted successfully!”);
// You can proceed with form submission or AJAX request here
// this.submit(); // Uncomment to submit the form
}
});
});
</script>
</body>
</html>
Explanation:
- HTML: Defines a registration form with name, email, and password fields.
- CSS: Styles the form and error messages, highlighting inputs based on validation status.
- jQuery:
- Handles the form submission event.
- Validates each field:
- Name: Must not be empty.
- Email: Must not be empty and should follow a valid email format.
- Password: Must not be empty and should be at least 6 characters long.
- Displays error messages next to invalid fields.
- Highlights valid and invalid inputs with CSS classes.
- Alerts the user upon successful validation.
Exercise 4: Image Slider
Objective: Create an image slider that automatically transitions between images and allows manual navigation using next and previous buttons.
Features:
- Automatic sliding of images every few seconds.
- Next and Previous buttons for manual control.
- Smooth transitions between slides.
Solution Outline:
- HTML Structure:
- Container for the slider.
- Images within the slider.
- Next and Previous buttons.
- CSS Styling:
- Position images absolutely within the container.
- Hide all images except the active one.
- Style navigation buttons.
- jQuery Functionality:
- Set up automatic slide transitions using setInterval.
- Handle click events on Next and Previous buttons to navigate slides.
- Implement smooth fade transitions.
Sample Code:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>jQuery Image Slider</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#slider {
position: relative;
width: 600px;
height: 400px;
margin: auto;
overflow: hidden;
}
#slider img {
position: absolute;
width: 100%;
height: 100%;
display: none;
}
#slider img.active {
display: block;
}
.nav-button {
position: absolute;
top: 50%;
transform: translateY(-50%);
background-color: rgba(0,0,0,0.5);
color: white;
padding: 10px;
cursor: pointer;
border: none;
}
#prev {
left: 10px;
}
#next {
right: 10px;
}
</style>
</head>
<body>
<div id=”slider”>
<img src=”images/slide1.jpg” class=”active” alt=”Slide 1″>
<img src=”images/slide2.jpg” alt=”Slide 2″>
<img src=”images/slide3.jpg” alt=”Slide 3″>
<button id=”prev” class=”nav-button”>Prev</button>
<button id=”next” class=”nav-button”>Next</button>
</div>
<script>
$(document).ready(function(){
let current = 0;
const slides = $(“#slider img”);
const total = slides.length;
const interval = 3000; // 3 seconds
let slideInterval = setInterval(nextSlide, interval);
function nextSlide(){
slides.eq(current).removeClass(“active”).fadeOut(1000);
current = (current + 1) % total;
slides.eq(current).addClass(“active”).fadeIn(1000);
}
function prevSlide(){
slides.eq(current).removeClass(“active”).fadeOut(1000);
current = (current – 1 + total) % total;
slides.eq(current).addClass(“active”).fadeIn(1000);
}
$(“#next”).click(function(){
clearInterval(slideInterval);
nextSlide();
slideInterval = setInterval(nextSlide, interval);
});
$(“#prev”).click(function(){
clearInterval(slideInterval);
prevSlide();
slideInterval = setInterval(prevSlide, interval);
});
});
</script>
</body>
</html>
Explanation:
- HTML: Defines the slider container with three images and navigation buttons.
- CSS: Positions images absolutely and hides them except for the active one. Styles the navigation buttons.
- jQuery:
- Keeps track of the current slide index.
- Sets up an interval to automatically transition to the next slide every 3 seconds.
- Defines nextSlide and prevSlide functions to handle slide transitions with fade effects.
- Binds click events to Next and Previous buttons to allow manual navigation, resetting the interval upon interaction.
Note: Ensure that the image paths (images/slide1.jpg, etc.) are correct and the images exist in the specified directory.
Exercise 5: AJAX-Based Search
Objective: Implement a live search feature that fetches and displays search results as the user types, using AJAX.
Features:
- Input field for search queries.
- Display of search results dynamically.
- Debounce input to minimize unnecessary AJAX requests.
Solution Outline:
- HTML Structure:
- Search input field.
- Container to display search results.
- CSS Styling:
- Style the search bar and results container.
- Highlight matching results.
- jQuery Functionality:
- Capture input events on the search field.
- Implement debounce to delay AJAX requests until the user stops typing.
- Perform AJAX requests to fetch search results.
- Display results dynamically in the results container.
Sample Code:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<title>AJAX-Based Live Search</title>
<script src=”https://code.jquery.com/jquery-3.6.0.min.js”></script>
<style>
#searchContainer {
max-width: 600px;
margin: 50px auto;
position: relative;
}
#searchInput {
width: 100%;
padding: 10px;
box-sizing: border-box;
font-size: 1em;
}
#results {
border: 1px solid #bdc3c7;
border-top: none;
max-height: 300px;
overflow-y: auto;
display: none;
position: absolute;
width: 100%;
background-color: white;
z-index: 1000;
}
.result-item {
padding: 10px;
cursor: pointer;
}
.result-item:hover {
background-color: #f1c40f;
color: white;
}
</style>
</head>
<body>
<div id=”searchContainer”>
<input type=”text” id=”searchInput” placeholder=”Search…”>
<div id=”results”></div>
</div>
<script>
$(document).ready(function(){
let debounceTimer;
$(“#searchInput”).on(“input”, function(){
clearTimeout(debounceTimer);
const query = $(this).val().trim();
if(query.length === 0){
$(“#results”).hide();
return;
}
debounceTimer = setTimeout(function(){
$.ajax({
url: “https://jsonplaceholder.typicode.com/posts”,
type: “GET”,
data: { q: query },
success: function(data){
const filtered = data.filter(post => post.title.includes(query));
displayResults(filtered);
},
error: function(){
$(“#results”).html(“<p>An error occurred while fetching results.</p>”).show();
}
});
}, 300); // 300ms debounce
});
function displayResults(data){
if(data.length > 0){
let html = “”;
data.forEach(function(item){
html += `<div class=”result-item” data-id=”${item.id}”>${item.title}</div>`;
});
$(“#results”).html(html).show();
} else {
$(“#results”).html(“<p>No results found.</p>”).show();
}
}
// Handle click on result items
$(“#results”).on(“click”, “.result-item”, function(){
const id = $(this).data(“id”);
alert(`You selected post ID: ${id}`);
$(“#results”).hide();
$(“#searchInput”).val(“”);
});
// Hide results when clicking outside
$(document).click(function(event) {
if(!$(event.target).closest(‘#searchContainer’).length) {
if($(‘#results’).is(“:visible”)) {
$(‘#results’).hide();
}
}
});
});
</script>
</body>
</html>
Explanation:
- HTML: Defines a search input and a container to display results.
- CSS: Styles the search bar and results dropdown, including hover effects.
- jQuery:
- Debounce Implementation: Prevents excessive AJAX calls by delaying the request until the user stops typing for 300ms.
- AJAX Request: Fetches posts from the JSONPlaceholder API and filters them based on the query.
- Display Results: Shows matching titles in the results container.
- Result Selection: Alerts the user with the selected post ID upon clicking a result.
- Click Outside to Hide: Hides the results dropdown when clicking outside the search container.
Note: Since JSONPlaceholder doesn’t support search queries, the example fetches all posts and filters them on the client side. For real-world applications, use an API that supports search functionality.
11. Multiple Choice Questions
Test your understanding of jQuery with the following multiple-choice questions. Answers and explanations are provided after each question.
Question 1
What is the correct jQuery syntax to hide all paragraphs on a webpage?
A) $(“p”).hide();
B) document.getElementsByTagName(“p”).hide();
C) hide(“p”);
D) #p.hide();
Answer: A) $(“p”).hide();
Explanation:
- $(“p”).hide(); correctly selects all <p> elements and applies the .hide() method.
- Option B: Uses vanilla JavaScript syntax, which doesn’t have a .hide() method.
- Option C: Incorrect usage; hide is a jQuery method that needs to be called on a jQuery object.
- Option D: #p selects an element with ID p, not all paragraphs.
Question 2
Which jQuery method is used to perform an AJAX GET request?
A) $.ajaxGet()
B) $.get()
C) $.post()
D) $.getJSON()
Answer: B) $.get()
Explanation:
- $.get() is the shorthand method for performing an AJAX GET request.
- Option A: $.ajaxGet() is not a valid jQuery method.
- Option C: $.post() is used for AJAX POST requests.
- Option D: $.getJSON() performs a GET request and expects a JSON response, but the general GET method is $.get().
Question 3
How do you select an element with the ID main using jQuery?
A) $(“main”)
B) $(“.main”)
C) $(“#main”)
D) document.getElementById(“main”)
Answer: C) $(“#main”)
Explanation:
- $(“#main”) correctly selects the element with ID main.
- Option A: $(“main”) selects all <main> elements.
- Option B: $(“.main”) selects elements with the class main.
- Option D: Uses vanilla JavaScript syntax, not jQuery.
Question 4
Which jQuery method is used to attach an event handler for the click event?
A) .on(“click”, handler)
B) .click(handler)
C) .bind(“click”, handler)
D) All of the above
Answer: D) All of the above
Explanation:
- .on(“click”, handler): The preferred modern method for attaching events.
- .click(handler): A shorthand method for attaching click events.
- .bind(“click”, handler): An older method, now deprecated in favor of .on().
- All these methods can attach a click event handler, but .on() is recommended.
Question 5
What does the jQuery $(document).ready() function ensure?
A) The entire webpage, including images and iframes, is fully loaded.
B) The DOM is fully loaded and can be manipulated.
C) All external scripts are loaded.
D) The user has interacted with the page.
Answer: B) The DOM is fully loaded and can be manipulated.
Explanation:
- $(document).ready() executes the provided function once the DOM is fully loaded, allowing safe manipulation of elements.
- Option A: Refers to the window.onload event, which waits for all resources to load.
- Option C & D: Not related to the ready() function.
Question 6
Which method is used to add a class to selected elements in jQuery?
A) .addClass()
B) .appendClass()
C) .classAdd()
D) .add()
Answer: A) .addClass()
Explanation:
- .addClass() correctly adds the specified class to each element in the set of matched elements.
- Option B, C, D: These are not valid jQuery methods for adding classes.
Question 7
How can you retrieve the value of an input field with the ID username?
A) $(“#username”).val();
B) $(“#username”).text();
C) document.getElementById(“username”).value;
D) Both A and C
Answer: D) Both A and C
Explanation:
- Option A: $(“#username”).val(); uses jQuery to get the value.
- Option C: document.getElementById(“username”).value; uses vanilla JavaScript to achieve the same.
- Option B: .text() retrieves the text content, not the value of form elements.
Question 8
Which of the following jQuery methods can be used to iterate over a set of elements?
A) .each()
B) .forEach()
C) .map()
D) Both A and C
Answer: D) Both A and C
Explanation:
- .each() iterates over matched elements and executes a function for each.
- .map() translates a set of elements into an array by applying a function to each element.
- .forEach() is a JavaScript array method, not a jQuery method.
Question 9
What is the purpose of the $.noConflict() method in jQuery?
A) To release jQuery’s control of the $ variable to avoid conflicts with other libraries.
B) To disable all jQuery plugins.
C) To prevent jQuery from loading.
D) To optimize jQuery for performance.
Answer: A) To release jQuery’s control of the $ variable to avoid conflicts with other libraries.
Explanation:
- $.noConflict() relinquishes jQuery’s hold on the $ identifier, allowing other libraries that use $ to function without interference.
Question 10
Which jQuery method removes the last element from the selected set of elements?
A) .remove()
B) .last()
C) .removeLast()
D) .pop()
Answer: A) .remove()
Explanation:
- .remove() removes the selected elements from the DOM. To remove the last element, you can combine it with the .last() selector: $(“selector”).last().remove();
- Option B: .last() selects the last element but does not remove it.
- Option C & D: These are not valid jQuery methods.
Question 11
Which jQuery method is used to retrieve the HTML content of an element?
A) .html()
B) .text()
C) .val()
D) .content()
Answer: A) .html()
Explanation:
- .html() retrieves or sets the HTML content of the selected elements.
- .text() retrieves or sets the text content without HTML tags.
- .val() is used for form elements to get or set their value.
- Option D: .content() is not a jQuery method.
Question 12
How do you stop an animation that is currently running on an element?
A) .stop()
B) .halt()
C) .pause()
D) .end()
Answer: A) .stop()
Explanation:
- .stop() immediately stops the currently running animation on the selected elements.
- Options B, C, D: These are not valid jQuery methods for stopping animations.
Question 13
Which method is used to send a POST request using jQuery?
A) $.post()
B) $.send()
C) $.ajaxPost()
D) $.submit()
Answer: A) $.post()
Explanation:
- $.post() is the shorthand method for performing an AJAX POST request.
- Options B, C, D: These are not valid jQuery methods for sending POST requests.
Question 14
What does the jQuery .data() method do?
A) Retrieves data stored in the DOM’s data attributes.
B) Stores arbitrary data associated with the matched elements.
C) Both A and B.
D) None of the above.
Answer: C) Both A and B.
Explanation:
- .data() can be used to store and retrieve arbitrary data associated with DOM elements, utilizing HTML5 data-* attributes or internal jQuery storage.
Question 15
Which jQuery method can be used to clone selected elements?
A) .duplicate()
B) .copy()
C) .clone()
D) .replicate()
Answer: C) .clone()
Explanation:
- .clone() creates a deep copy of the set of matched elements, including their child elements and event handlers if specified.
- Options A, B, D: These are not valid jQuery methods for cloning elements.
12. Conclusion
Congratulations! You’ve completed the comprehensive guide to jQuery. This guide has covered everything from the basics of jQuery syntax and selectors to advanced topics like event handling, DOM manipulation, AJAX, effects, plugins, and best practices. By working through the code examples, exercises, and multiple-choice questions, you’ve built a solid foundation in jQuery that will empower you to create dynamic and interactive web applications.
