Facebook Twitter Gplus LinkedIn RSS
 
 
Home » Blog » Using New jQuery 1.7 on() & off() Functions

Using New jQuery 1.7 on() & off() Functions

Published on April 15th, 2012

There are many ways in jQuery to “bind” ajax functions to events. With jQuery 1.7 and beyond, everything has been consolidated into the on() and off() functions. Everything else has been deprecated. No more live(), die(), bind(), unbind(), and delegate(). Not only does on() and off() replace these infamous functions, it has been optimized to run substantially faster.

Of course they left the old functions in the code so that Apps don’t immediately break with the update, but you shouldn’t wait to make the transition. The speed increase alone makes it worth your while, and in most cases, a simple swap of your live() and bind() functions with on() is enough to get you started. We even have a new one() function that allows you to run an ajax routine once, then remove it.

1
2
3
4
5
6
7
$('#someDiv').on( 'click', function(event) {
    //some code
});
 
$document.on( 'click', "#someDiv", function(event) {
    //some code    
});
$('#someDiv').on( 'click', function(event) {
    //some code
});

$document.on( 'click', "#someDiv", function(event) {
    //some code    
});

Be sure to read the full documentation to see other clever ways to use on() and off().

About the Author: Sprawl

Stephen Russell is a Mobile App developer and all around IT geek that spends his days running data centers and his nights coding. This site is the go to place for all of zSprawl’s work and the infamous development blog. In his free time, he enjoys tinkering with web code, playing video games, and otherwise plotting to take over the Internets.


 

Leave a Reply

© 2012 zSprawl's zApps

Fork me on GitHub