jQuery Events allow you to respond to user interactions like clicks, key presses, mouse movements, form submissions, and more. They make web pages interactive and dynamic with minimal JavaScript code.
Basic syntax for attaching an event in jQuery:
// Attach a click event to a button
$("button").click(function(){
alert("Button clicked");
});
click()dblclick()mouseenter()mouseleave()keydown()keyup()submit()change()
// Change text when paragraph is clicked
$("p").click(function(){
$(this).text("You clicked the paragraph");
});
When the paragraph is clicked, the text inside it changes instantly. This demonstrates how jQuery listens for events and executes callback functions.
// Button hover & click interaction
$("#demo-box").on({
mouseenter: function(){
$(this).css("opacity", "0.7");
$("#event-log").text("Event: Mouse Enter ?️");
},
mouseleave: function(){
$(this).css("opacity", "1");
$("#event-log").text("Event: Mouse Leave ?");
},
click: function(){
$(this).css("transform", "scale(0.95)");
$("#event-log").text("Event: Clicked! ?");
setTimeout(() => $(this).css("transform", "scale(1)"), 150);
}
});
on() for better flexibility