jQuery $.on Method

In a simple definition, you can say the $.on method is a longer version of event methods like click, dbclick, change, hover, keyUp, keyDown, and others.

jQuery allows you to use the shorthand of events like click event and other events. However, the .on method not only allows you to use these methods alone but you can also attach multiple event handlers by using it once.

For example, you want to perform the same action as the user clicks, changes or presses a key in an element.

Rather than writing the code for each event handler separately, you can specify all in a single jQuery $.on method. Similarly, you can perform different actions for different events by using a single $.on method.

The jQuery $.on method is more than that. From the 1.7 version of jQuery, the on method replaced delegate, live, and bind methods.

The examples in this tutorial will show you different forms of using .on jQuery method. You can also see how .on method replaces other methods of jQuery.

An example of jQuery on click

In this example, I will use the single event handler in .on (with click) method.

For that, I have created a div element with a border. As you click inside the div, an alert will be shown.

jquery onclick

jQuery Code for this example with HTML

<!DOCTYPE html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
    $(".clickcls").on("click",function(){
    alert("You have clicked inside Div!");
    });
});
</script>

<style>
.clickcls{
width:300px;
height:300px;
border: 1px solid blue;
}
</style>
</head>
<body>

<div class="clickcls">Click with on method example</div>

</body>
</html>

As you can see inside on method, the click event is given where an alert is also used:

$(“.clickcls”).on(“click”,function(){

The $.on method with click and change event handlers

In this example, I attached two event handlers i.e. on change and click. For that, I have created a text area element.

As you click inside the textarea, the alert will be shown as click event occurs. Similarly, the change event occurs as you change the text (type in something) and get out of the text area, the alert will be shown.

Note that, multiple event handlers are separated by space.

jquery onclick onchange

Complete Code:

<!DOCTYPE html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
    $(".clickcls").on("click change",function(){
    alert("Click or change event occured");
    });
});
</script>

<style>
.clickcls{
width:300px;
height:200px;
border: 2px solid red;
}
</style>
</head>
<body>

<textarea class="clickcls">Click and change with on method example <!--Closing tag of textarea here-->

</body>
</html>

As you can see, multiple events are specified after jQuery on method (change and click) as follows:

$(“.clickcls”).on(“click change”,function()

Specifying multiple handlers is quite useful to perform the same action for different events. You can specify even more event handlers, just separate it by spaces. See this line:

$(“.clickcls”).on(“click change mouseenter”,function(){

You can see the .on with change, click, and mousenter. Now alert will be triggered as the mouse enters the textarea, as well.

An example of .on with colored div

In this example of jQuery on method, I have created five different colored div and a larger div to the right.

The right div is kept white. I used $.on jQuery method with each div element and used different event handlers for the div as follows:

A Gif showing jQuery $.on method demonstration on the click and mouse over events.

As you bring the mouse over red div, the color of the larger div will be changed to red as I used $.on with mouseenter and click events.

The green div color will be changed with a double click  –

$(“#div2”).on(“dblclick”, function()

As you leave the mouse from the third div (which is yellow) the color of the right div will be changed to the yellow because $.on method is attached to mouseleave event.

The last two div again use mouseneter and click respectively to change the color of the right div.

Full code:

<!DOCTYPE html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
    $("#div1").on("click mouseenter", function(){
    $("#chgcolor").css("background-color","red");
    });
    
    $("#div2").on("dblclick", function(){
    $("#chgcolor").css("background-color","green");
    });
    
    $("#div3").on("mouseleave", function(){
    $("#chgcolor").css("background-color","yellow");
    });
    
    $("#div4").on("mouseenter", function(){
    $("#chgcolor").css("background-color","blue");
    });
    
    $("#div5").on("click", function(){
    $("#chgcolor").css("background-color","black");
    });
});
</script>

<style>
#div1{
width:30px;
height:50px;
background-color:red;
}
#div2{
width:30px;
height:50px;
background-color:green;
}
#div3{
width:30px;
height:50px;
background-color:yellow;
}
#div4{
width:30px;
height:50px;
background-color:blue;
}
#div5{
width:30px;
height:50px;
background-color:black;
}
#chgcolor{
width:200px;
height:200px;
background-color:white;
border:1px solid black;
margin-top:-250px;
margin-left:100px
}
</style>
</head>
<body>

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<div id="div5"></div>

<div id="chgcolor"></div>


</body>
</html>

Different functionality to events in $.on method example

In above examples, I have attached the same event handler to multiple events.

  • By using jQuery $.on method, you can attach multiple events with different functionality as well.
  • For example, doing some action as mouseenter event takes place inside a div element like fading in its background color and returning it to the same color as mouseleave event occurs in that div.
  • The following example shows how to use different functionality for different events.

jquery on diff functions

jQuery Code with HTML:

<!DOCTYPE html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){

    $( "#div1" ).on({
      mouseenter: function() {
        $("#chgcolor").css("background-color","red");
      }, mouseleave: function() {
        $("#chgcolor").css("background-color","white");
      }
    });

});
</script>

<style>
#div1{
width:30px;
height:50px;
background-color:red;
}

#chgcolor{
width:100px;
height:100px;
background-color:white;
border:1px solid black;
margin-top:-50px;
margin-left:100px
}
</style>
</head>
<body>

<div id="div1"></div>
<div id="chgcolor"></div>


</body>
</html>

You can see as you bring the mouse inside the red div the color of the right div is changed to red and as you bring the mouse out of the left div the color of right div will be changed to white.

This is done by using the following code:

mouseenter event:

mouseenter: function() {

        $("#chgcolor").css("background-color","red");

mouseleave event:

mouseleave: function() {

        $("#chgcolor").css("background-color","white");

$.on method as replacement of live method example

As such the live method attaches one or more event handlers to the specified element that executes for the parent as well as current or future child elements as well.

From 1.9 version of the jQuery, this method is removed and replaced by $.on jQuery method.

The following example shows how .on method is used to replace live method of jQuery.

In the example, I have created a parent div element with a child paragraph. Inside the script section, the .on method is used to create the future child elements, i.e. paragraphs of div. A function, on_livefunction is created that shows an alert which is called in $.on method.

jquery on Live

Code that you can copy and try in your editor:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){

$('#on_livediv').on('click', on_livefunction);
  $('#on_livediv').click(function(){
    $("<p>The new paragraph, or child element of Div</p>").insertAfter("#livep");
  });
});
 
function on_livefunction() {
    alert("parent or child paragraph clicked");
  }
 
</script>
<style>
#on_livediv{
width:250px;
font-weight:bold;
font-size:15px;
padding:10px;
border:1px solid red;
}
p{
width:200px;
font-weight:normal;
border:1px solid green;
padding:2px;
}
</style> 
</head>
 
<body>

<div id="on_livediv">Parent Div element
<p id="livep">Paragraph - child of parent div </p>
</div>

 
</body>
 
</html>

When you click on div or paragraph the alert will be shown in both cases. You have to specify event name(s) and function in jQuery .on method as I did in this line:

$(‘#on_livediv’).on(‘click’, on_livefunction);

When you click on new paragraphs (child of div), the function will be called and executed and an alert will be shown just like in the parent div element.

In case, you do not want to execute a function or event handler to the parent element and just to child elements, jQuery has delegate method which is also replaced by $.on method. See the next section to learn how $.on method replaced the delegate method.

$.on method as replacement of delegate method

In the $.delegate method, the event handler is attached to child element(s) of the specified element. The child element(s) can be current or future elements.

However, from 1.7 version of jQuery the preferred method to accomplish this task is by using $.on method.

If you have gone through the above example of using .on as a replacement for the .live method then it is quite easier to understand. You simply need to specify child element after giving event names in the parameters section of jQuery on method.

jquery on delegate

Code:

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){

$('#on_delegatediv').on('click', 'p', on_livefunction);
  $('#on_delegatediv').click(function(){
    $("<p>The new paragraph, or child element of Div</p>").insertAfter("#livep");
  });
});
 
function on_livefunction() {
    alert("Child paragraph clicked");
  }
 
</script>
<style>
#on_delegatediv{
width:250px;
font-weight:bold;
font-size:15px;
padding:10px;
border:1px solid red;
}
p{
width:200px;
font-weight:normal;
border:1px solid green;
padding:2px;
}
</style> 
</head>
 
<body>

<div id="on_delegatediv">Demo of $.on as replacement of delegate! Click on div text
<p id="livep">Paragraph - child of parent div </p>
</div>

 
</body>
 
</html>

If you click on div text where it says “Demo of $.on as replacement of delegate! Click on div text” or paragraph, a new paragraph will be added by using insertAfter in the script section, which is the future child of parent div. However, note the difference in code and output than the above example here:

$(‘#on_delegatediv’).on(‘click’, ‘p’, on_livefunction);

Where I specified ‘p’ as the child in $.on method. If you click on div text, no alert will be shown and just paragraph will be inserted.

However, as you click on the current or new paragraph, an alert will be shown along with a new paragraph will be added. While in the case of $.live replacement of $.on example, the div was also showing an alert which means event handler (the function) was executing for both parent and child while in this case event handler only executed for the child element.

An example of $.on method with button click and animation

This is a more interactive example of using the .on method of jQuery. In this example, I will create an animation by using a div element. The $.animate method of jQuery is used to create that animation. The $.on method is linked with the button’s click event.

As you click on the button, the .on method will attach an event handler on click event of the button. Have a look at live demo of this example along with code:

An demo of $.on method (in gif) with button click and animation

The code:

<!doctype html>
<html>
<head>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"> </script> 
<script>
   $(document).ready(function() {

    $( "#runani" ).on("click",function() {
        animateex();
    });        
  function animateex() {       
      $( "#divanimation" ).animate({
        opacity: 0.6,
        width: "160",
        height: "160",
        backgroundColor:"#FBE9AC",
        color:"#000",
        lineHeight: "75px",
        fontSize:"10px"
      },3000,animateback);
    }

  function animateback() {       
      $( "#divanimation" ).animate({
        opacity: 1,
        width: "250px",
        height: "250px",
        backgroundColor:"#2B5F8E",
        color:"#fff",
        lineHeight: "150px",
        fontSize:"25px"
      },3000,animateex);
    }
    
});

</script>
  <style>
#divanimation {
    padding: 8px;
    background:#2B5F8E;
    width: 250px;
    height:250px;
    box-shadow: 0 0 5px #aaa;
    font-size: 25px;
    color:#fff;
    text-align:center;
    border-radius: 150px;
    line-height: 150px;
}

button{
   margin: 30px; 
}
  </style>
</head>
<body>

<div id="divanimation">Button with $.on Click</div>
<button id="runani">Click to Start Animation</button>

</body>
</html>

As you can see, the jQuery on method specifies a click event along with calling a function animateex. The animateex uses the $.animate method that changes div properties and after completing, the animation calls another function animateback that takes the animation back to its original style at the end it also calls animateex function, so the process goes on.

Also note that for color animation, I have included the jQuery UI library in the above demo.