Converting to `on()`

jQuery 1.7 introduced new methods for handling DOM events in JavaScript; on() and off(). In this article we will focus on on().

It is intended that, from now on, on() should be used where you’d previously have used any of bind(), live(), delegate(). In particular, live() has been depreciated already; so usage of this in your projects should cease immediately. Converting from any of these methods to on() is easy; you just have to follow the following conversion rules:

  1. If you were previously using bind(), simply change the function name to on(); on() supports the same method signatures as bind().

    $('.foo').bind('click', function () { 
        alert('Hello'); 
    })`;
    

    … will now be…

    $('.foo').on('click', function () { 
        alert('Hello'); 
    });
    
  2. If you were previously using delegate(selector, map), where selector identified the elements whose events you wanted to handle, and map was an object which mapped event types to handlers, swap the selector and map arguments around.

    $('div').delegate('a', {
        mouseover: function () {
            alert('Mouse Over!')'            
        },
        mouseleave: function () {
            alert('Mouse Out!')'
        }
    }); 
    

    … will now be…

    $('div').on({
        mouseover: function () {
            alert('Mouse Over!')'            
        },
        mouseleave: function () {
            alert('Mouse Out!')'
        }
    }, 'a'); 
    
  3. All other uses of delegate() can be converted to on() by swapping the order of the first two parameters (the selector and event list)

    $('div').delegate('a', 'click', function () { 
        alert('Clicked!'); 
    });
    

    … will now be…

    $('div').on('click', 'a', function () {
        alert('Clicked!');
    });
    
  4. All uses of live() can be converted to use on() by inserting the selector as the second argument to on(), and setting what-used-to-be-the-selector to document:

    $('a').live('click', function () { 
        alert('Clicked!'); 
    });
    

    … will now be…

    $(document).on('click', 'a', function () {
        alert('Clicked!');
    });
    

.. and that’s all there is to it! To find out more about the new function on(), you can read it’s extensive documentation on the jQuery website.

Leave a Reply

Your email address will not be published. Required fields are marked *