jQuery event helpers
Posted on September 28, 2011 | Comments Off on jQuery event helpers
.live()
This method attach a handler to the event for all elements which match the current selector, now or in the future.
Example :
Following code binds the click event to all paragraphs. And add a paragraph to another clicked paragraph :
Click me!
.die( )
This method removes the handler which is previously attached using ‘live( )’ from the elements.
Example :
Following code binds and unbinds events to the buttons :
$(“#bindbutton”).click(function () {
$(“#button1”).live(“click”, aClick)
.text(“Can Click!”);
});
$(“#unbindbutton”).click(function () {
$(“#button2”).die(“click”, aClick)
.text(“Does nothing…”);
});
Here ‘aclick’ is a user defined function which display a ‘div’ on button click. Using ‘die’ it detach the click event from ‘aClick’ function.
.one( )
This method attach the element with an event. The main difference between it and ‘.bind()’ is that it will execute only once .After this , it is unbind automatically.
Example :
Following code will display an alert box on clicking element ‘foo’ :
$(‘#foo’).one(‘click’, function() {
alert(‘This will be displayed only once.’);
});
jQuery.proxy( )
This method takes a function and returns a new one that will always have a particular scope.
Example :
It will enforce the function :
var obj = {
name: “John”,
test: function() {
alert( this.name );
$(“#test”).unbind(“click”, obj.test);
}
};
$(“#test”).click( jQuery.proxy( obj, “test” )
.trigger( )
This method executes the event which is attached with the matched elements.
Example :
Following code triggered the click event on ‘foo’ element manually .
$(‘#foo’).bind(‘click’, function() {
alert($(this).text());
});
$(‘#foo’).trigger(‘click’);