Javatpoint Logo
Javatpoint Logo

jQuery on() method

The on() method is used to attach event handlers to the selected elements. The on() method replaces delegate(), bind(), and live() methods. This method is recommended to be used as it simplifies the jQuery code base. We can use the off() method to remove the event handlers attached by the on() method.

It is an inbuilt method in jQuery. The syntax of using the on() method is given as follows -

Syntax

This method accepts five parameters in which one is mandatory, and others are optional. The parameter values of the on() method are defined as follows.

event: It is the mandatory parameter. This parameter specifies one or multiple events or namespaces to attach to the selected elements. If we have to specify multiple events, the event values must be separated by a space.

childSelector: It is an optional parameter. It specifies the child elements to which the event handler is to be attached.

data: It is also an optional parameter. It is the additional data to be passed to the handler when an event is triggered.

function(eventObj): It is also an optional parameter. It is the function to run when an event triggers.

map: It is the event map.

Now, let's see some illustrations to understand the use of the on() method.

Example1

In this example, there is an h3 heading element on which we are applying the on() method to attach the click event to it. We have to click the h3 element texted as Click me to see the effect.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery on() method

After clicking the given text Click me, an alert dialog box will be displayed as follows -

jQuery on() method

Example2

In the previous example, we have attached a single event handler to the selector. But in this example we will see how to attach multiple event handlers to the selected element.

Here, there is a div element on which we are applying the on() method to add three events that are mouseover, mouseout, and click. When we move the cursor over the given text "This is a div element", the style and text of the element will get changed, and the events mouseover, mouseout, and click will be attached to it.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery on() method

When we move the cursor over the text This is a div element, the output will be -

jQuery on() method

After clicking the text Click me, the output will be -

jQuery on() method

Example3

In this example, we are attaching a custom event to the div element using the on() method.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery on() method

After clicking the given button, the output will be -

jQuery on() method




Youtube For Videos Join Our Youtube Channel: Join Now

Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA