Tuesday, 15 May 2012

jQuery Event Handling

Jquery provides methods are used to register behaviors to take effect when the user interacts with the browser, and to further manipulate those registered behaviors.



.bind() Attach a handler to an event for the elements.


<input type=“button” id=“myButton” value=“GO”/>
$(‘#myButton').bind('click', function() {
                alert('User clicked on "foo."');
});


Bind Multiple Events
$(‘#myButton').bind('mouseenter mouseleave', function() {
                alert(‘Action Performed');
});


.unbind() Remove a previously-attached event handler from the elements.
$(‘#myButton').unbind('click');

Events


event.preventDefault() If this method is called, the default action of the event will not be triggered.
<a href="http://jquery.com">jquery home page</a> 
$("a").click(function(event) {   
                event.preventDefault(); 
                alert(“default prevented”);
});


.trigger() Execute all handlers and behaviors attached to the matched elements for the given event type.
$('#myButton').bind('click', function() {
                alert($(this).text());
});
$('#myButton').trigger('click');

.live() Attach a handler to the event for all elements which match the current selector, now and in the future.
<span class=“clickme”> CLICK ME</span>
$('.clickme').live('click', function() {
                 // Live handler called.
});
$('body').append('<div class="clickme">Another target</div>');


.die() Remove all event handlers previously attached using .live() from the elements.
$('.clickme').die('click‘);

Few event methods available in jquery
.blur()
.change()
.click()
.dblclick()
.keydown()
.keypress()
.keyup()
.mousedown()
.mouseenter()
.mousemove()
.mouseout()
.mouseover()
.mouseup()

Usage:
$('#myButton').dblclick(function() {
                alert('Handler for .mousedown() called.');
});