.bind()
methodThe .bind()
method in jQuery is used to set event hanlder for the matched elements.
Use .unbind()
or .off()
to remove the attached event handler.
.bind()
method Syntax.bind(eventType,handler) .bind(eventType,eventData,handler) .bind(eventType,eventData) .bind(eventType,eventData,preventBubble) .bind(events)
Parameter | Type | Description |
---|---|---|
eventType |
String | event Type such as 'click','submit' |
handler |
Function | event handler function |
eventData |
Anything | the data passed to event handler |
preventBubble |
Boolean | whether to prevent the default action |
events |
Object | contains event type and function handler |
.bind()
method Examplewhen the user clicks any paragraph, shows its text contents as an alert.
$( "p" ).bind( "click", function() { alert( $( this ).text() ); });
bind multiple event types
$('#foo').bind('mouseenter mouseleave', function() { $(this).toggleClass('entered'); });
bind multiple event handlers simultaneously
$("button").bind({ click:function(){$("p").slideToggle();}, mouseover:function(){$("body").css("background-color","red");}, mouseout:function(){$("body").css("background-color","#FFFFFF");} });
You can pass some external data to the event handler.
function handler(event) { alert(event.data.foo); } $("p").bind("click", {foo: "bar"}, handler)
use return false
to prevents the default action from occurring and stops the event from bubbling.
$("form").bind("submit", function() { return false; })
It's equivalent to calling both event.preventDefault()
and event.stopPropagation()
$("form").bind("submit", function(event) { event.preventDefault(); event.stopPropagation(); })