jQuery Tutorial Tutorials - jQuery .bind() method

jQuery .bind() method

The .bind() method in jQuery is used to set event hanlder for the matched elements.

Use .unbind() or .off() to remove the attached event handler.

jQuery .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

jQuery .bind() method Example

example

when the user clicks any paragraph, shows its text contents as an alert.

$( "p" ).bind( "click", function() {
  alert( $( this ).text() );
});

Try now

example

bind multiple event types

$('#foo').bind('mouseenter mouseleave', function() {
  $(this).toggleClass('entered');
});

Try now

example

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");}  
});

Try now

example

You can pass some external data to the event handler.

function handler(event) {
  alert(event.data.foo);
}
$("p").bind("click", {foo: "bar"}, handler)

example

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();
})
Date:2019-08-29 20:11:02 From:www.Lautturi.com author:Lautturi