jquery on method

3 Min. Read
Sep 2, 2019

Jquery’s On Method to Bind Event Handlers

on() and off methods in jquery replace previously used bind() and unbind() methods to bind event handlers to html elements in jquery. The syntax for the former are similar to that of the latter.

Let’s take a look at an example of on() method in action:

1
2
3
4
5
6
7
8
9
10
11
12
   $('#btnClickMe').on('click mouseover mouseout', function(e) {
        if(e.type == 'click') {
            $('#result').html('Button clicked at X - ' + e.pageX + 'Y = ' + e.pageY);
        }
        else if(e.type == 'mouseover') {
            $(this).addClass('ButtonStyle');
        }
        else {
            $(this).removeClass('ButtonStyle');
        }
    });

When any of three events click, mouseover or mouseout occurs, it executes the same anonymous function.

To remove event binding we use off() method

1
2
3
4
5
  $('#btnDisableMouseOverEffect').click(function() {
        $('#btnClickMe').off('mouseover');
  }

Let`s refactor our code a bit, instead of using the same anonymous function, we can do:

1
2
3
4
5
6
7
8
9
10
11
   $('#btnClickMe').on({
        click: function(event) {
            $('#result').html('Button clicked at X - ' + e.pageX + 'Y = ' + e.pageY);
            },
        mouseover: function(event) {
            $(this).addClass('ButtonStyle');
            },
        mouseout: function(event) {
            $(this).removeClass('ButtonStyle');
            }
        });

Shorthand functions like .click() , .mouseover() , .mouseout() call on()` function behind the scene.

Problem with attaching event handlers to elements:

When an event is associated with an html element, when the DOM loads, the event is attached to the element and the corresponding function is triggered whenever the event is fired. The problem with this is when we’re dealing with elements change throughout the life of the program, or in other words, elements that are added in the future, or elements that are dynamically loaded to the DOM with ajax calls. Since the elements are not initially present in the DOM, there’s no way we can attach event handlers to such elements. Or is there?

The WorkAround

You may have heard of Event Bubbling, which is a feature of javascript. When an event is attached to a Document element and it is invoked, the event itself doesn’t stop at that target element, the event bubble up to the DOM tree to parents and grandparents, and those parents and grandparent elements can handle the same event. So, instead of registering event handlers to each individual elements, we can register it on the parent element. This also helps us to write cleaner code. However, events such as focus, blur and scroll don’t bubble up the tree. To stop the event bubbling, we use event.stopPropagation(). Similarly, event delegation allows us to attach a single event listener to a parent element that will trigger for all the descendants matching a specified selector, event the ones that are to be added in the future. We attach the event handler to a parent element that isn’t subject to change as opposed to elements that can be changed throughout the life of the DOM.

In jQuery

When using jQuery, both on() and delegate() functions allow us to perform event delegation. If you have a lot of dynamic elements in your application. For Example:

1
2
3
4
5
6
7
  <body>
    <input id="btnAdd" type="button" value="Add a new list item" />
    <ul>
        <li>List Item</li>
        <li>List Item</li>
    </ul>
  </body>
1
2
3
4
5
6
7
8
9
  $(document).ready(function() {
    $('ul').on('click', 'li', function() {
    $(this).fadeOut(500);
    });
   });

  $('#btnAdd').on('click', fcuntion(){
    $('ul').append('<li>NewListIem</li>');
    }