Module 44: Interactive HTML with jQuery
Introduction to jQuery
jQuery is a lightweight JavaScript library that simplifies tasks such as DOM manipulation, event handling, and animations. It allows developers to interact with HTML elements efficiently.
Why Use jQuery?
Simplifies JavaScript code
Reduces cross-browser issues
Makes event handling easier
Provides built-in animations and effects
Enhances AJAX requests for dynamic content
1. Setting Up jQuery
Before using jQuery, include the jQuery library in your HTML file.
Using a CDN
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Setup</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Hello, jQuery!</h1>
</body>
</html>
Now you can use jQuery inside your <script> tag.
2. Selecting and Manipulating HTML Elements
Basic jQuery Selectors
jQuery uses $(selector).action() to interact with elements.
Selector Description
$("p") Selects all <p> elements
$("#id") Selects elements with a specific ID
$(".class") Selects elements with a specific class
$("*") Selects all elements
$("p:first") Selects the first <p> element
Example: Changing Text and CSS
<button id="changeText">Change Text</button>
<p id="text">Original Text</p>
<script>
$(document).ready(function() {
$("#changeText").click(function() {
$("#text").text("Text changed using jQuery!").css("color", "red");
});
});
</script>
Explanation:
$(document).ready() ensures the DOM is fully loaded before running jQuery.
$("#changeText").click() binds a click event to the button.
$("#text").text("New Text") changes the text content.
.css("color", "red") modifies the CSS.
3. Handling Events in jQuery
jQuery provides methods to handle user interactions like clicks, keypresses, and hovers.
Example: Show/Hide a Paragraph
<button id="toggle">Show/Hide</button>
<p id="info">This is a toggleable paragraph.</p>
<script>
$(document).ready(function() {
$("#toggle").click(function() {
$("#info").toggle();
});
});
</script>
Explanation:
.toggle() switches visibility when the button is clicked.
Other Event Methods
Method Description
.click() Fires when an element is clicked
.hover() Triggers when mouse enters/leaves an element
.keypress() Detects keyboard input
.focus() Runs when an input field is selected
4. Animations and Effects
jQuery provides built-in animations like .fadeIn(), .fadeOut(), .slideDown(), and .slideUp().
Example: Fade In and Out
<button id="fade">Fade Out</button>
<div id="box" style="width:100px; height:100px; background:blue;"></div>
<script>
$(document).ready(function() {
$("#fade").click(function() {
$("#box").fadeOut(1000);
});
});
</script>
Explanation:
.fadeOut(1000) makes the div disappear over 1 second.
5. Working with Forms
Example: Validating Form Input
<form id="myForm">
<input type="text" id="name" placeholder="Enter name">
<button type="submit">Submit</button>
</form>
<p id="error"></p>
<script>
$(document).ready(function() {
$("#myForm").submit(function(event) {
event.preventDefault();
let name = $("#name").val();
if (name === "") {
$("#error").text("Name is required!").css("color", "red");
} else {
$("#error").text("Form submitted!").css("color", "green");
}
});
});
</script>
Explanation:
.val() gets or sets input values.
event.preventDefault() stops the default form submission.
.text() updates the error message dynamically.
6. AJAX with jQuery
jQuery simplifies AJAX requests to fetch and display data without reloading the page.
Example: Fetching Data from an API
<button id="loadData">Load Data</button>
<div id="content"></div>
<script>
$(document).ready(function() {
$("#loadData").click(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts/1",
method: "GET",
success: function(response) {
$("#content").html(`<h3>${response.title}</h3><p>${response.body}</p>`);
}
});
});
});
</script>
Explanation:
$.ajax({}) sends a request to an API.
url specifies the API endpoint.
success: runs when data is retrieved successfully.
Exercises for Practice
Exercise 1: Image Slider
Create buttons to move images left and right.
Use .animate() to shift the images.
Exercise 2: Live Character Counter
Count and display the number of characters typed in a textbox.
Exercise 3: Todo List
Add an item to a list when clicking a button.
Remove items when clicked.
Guidance Counselor Review
What You Should Know Now
✅ Select and manipulate HTML elements using jQuery
✅ Handle user interactions with event listeners
✅ Create animations and effects
✅ Work with forms and validate input
✅ Fetch and display data using AJAX
Next Steps
Explore jQuery plugins like jQuery UI for advanced UI elements.
Learn jQuery Mobile for responsive designs.
Practice integrating jQuery with Bootstrap.
No comments:
Post a Comment