jQuery & DOM Manipulation
jQuery Events Basics
Introduction to jQuery Events
Events are actions or occurrences that happen in the browser - like clicking a button, hovering over an element, or loading a page. jQuery provides powerful methods to handle these events efficiently.
Why Use jQuery for Events?
- Cross-browser compatibility: Works consistently across all browsers
- Simplified syntax: Cleaner and more readable code
- Multiple handlers: Attach multiple event handlers to the same element
- Event delegation: Handle events for dynamically added elements
Basic Event Methods
jQuery provides shorthand methods for common events:
Click Event:
<button id="myButton">Click Me</button>
<script>
$(document).ready(function() {
$("#myButton").click(function() {
alert("Button clicked!");
});
});
</script>
The .on() Method
The .on() method is the recommended way to attach event handlers. It's more flexible and supports event delegation.
Using .on() for Click Event:
$("#myButton").on("click", function() {
console.log("Button clicked using .on()");
});
Best Practice: Use
.on() instead of shorthand methods like .click() for better flexibility and consistency.
Common Event Types
Mouse Events:
// Click event
$(".box").on("click", function() {
$(this).css("background-color", "var(--primary)");
});
// Double click event
$(".box").on("dblclick", function() {
$(this).css("background-color", "red");
});
// Mouse enter/leave
$(".box").on("mouseenter", function() {
$(this).addClass("hover");
}).on("mouseleave", function() {
$(this).removeClass("hover");
});
Hover Event (Shortcut):
$(".box").hover(
function() {
// Mouse enter
$(this).css("opacity", "0.8");
},
function() {
// Mouse leave
$(this).css("opacity", "1");
}
);
Document Ready Event
The most important jQuery event - ensures the DOM is fully loaded before executing code:
Three Ways to Write Document Ready:
// Method 1 (Full)
$(document).ready(function() {
// Your code here
});
// Method 2 (Short)
$(function() {
// Your code here
});
// Method 3 (ES6 Arrow Function)
$(() => {
// Your code here
});
The "this" Keyword in Event Handlers
Inside an event handler, this refers to the DOM element that triggered the event:
Using "this" Keyword:
<button class="btn">Button 1</button>
<button class="btn">Button 2</button>
<button class="btn">Button 3</button>
<script>
$(".btn").on("click", function() {
// "this" is the clicked button DOM element
// $(this) converts it to a jQuery object
$(this).css("background-color", "green");
$(this).text("Clicked!");
});
</script>
Arrow Functions Warning: Don't use arrow functions when you need
this to refer to the element. Arrow functions don't have their own this binding.
Chaining Multiple Events
Chaining Event Handlers:
$("#myElement")
.on("mouseenter", function() {
$(this).addClass("highlight");
})
.on("mouseleave", function() {
$(this).removeClass("highlight");
})
.on("click", function() {
$(this).toggleClass("active");
});
Removing Event Handlers
Use .off() to remove event handlers:
Removing Events:
// Remove all click events
$("#myButton").off("click");
// Remove specific handler
function myHandler() {
console.log("Clicked");
}
$("#myButton").on("click", myHandler);
$("#myButton").off("click", myHandler);
// Remove all events
$("#myButton").off();
Practical Example: Interactive Counter
HTML:
<div class="counter">
<button id="decrease">-</button>
<span id="count">0</span>
<button id="increase">+</button>
<button id="reset">Reset</button>
</div>
jQuery:
$(document).ready(function() {
let count = 0;
$("#increase").on("click", function() {
count++;
$("#count").text(count);
});
$("#decrease").on("click", function() {
count--;
$("#count").text(count);
});
$("#reset").on("click", function() {
count = 0;
$("#count").text(count);
});
});
Practice Exercise:
Task: Create an interactive color palette:
- Create 5 div elements with different background colors
- When a color is clicked, apply that color to a larger preview box
- Add a "Reset" button to clear the preview box
- Display the color name when hovering over each color
Bonus: Add a double-click event that adds the color to a favorites list.
Key Takeaways
- Use
.on()for attaching event handlers - Always wrap code in
$(document).ready() $(this)refers to the element that triggered the event- Use
.off()to remove event handlers - Avoid arrow functions when you need the
thiscontext