Events are the heart of web interactivity. They represent every action a user takes on your website — whether it's moving the mouse, clicking a button, or typing into a form. jQuery makes it incredibly simple to listen for these actions and respond to them with custom code.
An event represents the precise moment when something happens. In web development, we say that an event "fires" or "triggers." For example:
Events in jQuery are typically grouped into four main categories. Here are the most frequently used methods for each:
In jQuery, most events have a specific method name. To "attach" an event to an element, you use the following syntax:
$(selector).eventMethod(function() {
// Code to execute when the event happens
});
For example, to hide all paragraphs when they are clicked:
$("p").click(function() {
$(this).hide();
});
$(this) refers to the specific element that triggered the event. This is
extremely useful when applying actions to one specific item in a list.
You can also use the on() method to attach one or more event handlers for
the selected elements. This is the modern and preferred approach for complex
interactions.
$("p").on({
mouseenter: function() {
$(this).css("background-color", "lightgray");
},
mouseleave: function() {
$(this).css("background-color", "white");
},
click: function() {
$(this).css("background-color", "yellow");
}
});
The click() method attaches a function to run when the user clicks on an
HTML element.
The dblclick() method triggers when the user double-clicks on an element.
These fire when the mouse pointer enters or leaves the element's area. They are often used to create "hover" effects without using CSS.
The hover() method takes two functions and is a combination of
mouseenter() and mouseleave().
$("#target").hover(
function() { alert("You entered!"); },
function() { alert("You left!"); }
);
$(document).ready().$(this) keyword is your best friend for targeting triggered
elements.on() for attaching multiple events or working with dynamic content.