jQuery — Events
Click Event
$("button").click(function() {
$(this).text("Clicked!");
});
on() Method
The modern way to bind events:
$("button").on("click", function() {
$(this).toggleClass("active");
});
// Multiple events
$("input").on("focus blur", function() {
$(this).toggleClass("focused");
});
Common Events
| Event | Description |
|---|---|
| click | Mouse click |
| dblclick | Double click |
| mouseenter | Mouse enters element |
| mouseleave | Mouse leaves element |
| hover | Mouse enter + leave |
| focus | Element gains focus |
| blur | Element loses focus |
| keydown | Key pressed down |
| keyup | Key released |
| submit | Form submitted |
| change | Input value changed |
| scroll | Page scrolled |
Event Object
$("button").on("click", function(event) {
console.log(event.type); // "click"
console.log(event.target); // The clicked element
console.log(event.pageX); // Mouse X position
});
Preventing Defaults
$("a").on("click", function(event) {
event.preventDefault();
console.log("Link click blocked");
});
Stopping Propagation
$("div").on("click", function() {
console.log("Div clicked");
});
$("button").on("click", function(event) {
event.stopPropagation();
console.log("Button clicked only");
});
Event Delegation
Bind to a parent for dynamically added elements:
$("ul").on("click", "li", function() {
$(this).toggleClass("selected");
});
Unbinding Events
$("button").off("click");
$("button").off(); // Remove all events
One-Time Events
$("button").one("click", function() {
$(this).text("Only once!");
});
Mini Practice
- Bind a click event to a button
- Use on() for multiple events
- Prevent a link's default behavior
- Use event delegation on a list
Up Next
Continue with Effects — visual effects and animations.
Related Topics
Frequently Asked Questions about Events
What is Events in jQuery?
Events is a fundamental concept in jQuery. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Events?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Events.
Why is Events important in jQuery?
Events is essential for jQuery development. Understanding this concept will help you write better code and solve real-world problems more effectively.