What are Events and Event Handlers?
Learn about events, event handlers, and the event object in jQuery.
We'll cover the following
What is an event?
A web page consists of elements such as buttons, text boxes, paragraphs, links, images, forms, etc. A user interacts with these elements by performing numerous actions. These actions include but are not limited to clicking on elements, typing in text boxes, and hovering the mouse over elements. These actions are examples of events performed on a web page.
An event is a user action that prompts a web page response.
The different types of jQuery events are shown below. We will primarily focus on mouse and keyboard-based events.
What is an event handler?
As mentioned above, a user may perform countless events on a web page. This raises two important questions:
- How do you detect if a certain event is triggered?
- How do you respond to a triggered event?
This is where event handlers come into play.
An event handler continuously listens for the specified event on a given element. As soon as the event is triggered, the event handler executes the response defined in the event handler function.
Check out the illustration below for an example.
Defining an event handler
In jQuery, we assign an event handler like this:
$('selector').eventName(function(eventObj){
// response to event goes here
});
This can also be achieved with the on
method:
$('selector').on('eventName', function(eventObj){
// response to event goes here
});
In the code below a click
event handler for the button element listens for the button click. Once the button is clicked, the event handler responds by generating an alert box.
Within the event handler, we can access the selector by using $(this)
. In the code below, we will change the text
of a button once clicked. $(this)
is helpful here
The event object
The event handler function, by default, receives the event object as an argument. This object contains different properties that can be accessed within the event handler function. The event object, along with its properties, can be used for several important tasks.
In the code below, we print some useful properties of the event object. You can see these properties in the console as soon as the button is clicked.