jQuery API

.bind()

.bind( eventType [, eventData] , handler(eventObject) ) Returns: jQuery

Description: Attach a handler to an event for the elements.

  • version added: 1.0.bind( eventType [, eventData], handler(eventObject) )

    eventTypeA string containing one or more DOM event types, such as "click" or "submit," or custom event names.

    eventDataA map of data that will be passed to the event handler.

    handler(eventObject)A function to execute each time the event is triggered.

  • version added: 1.4.3.bind( eventType [, eventData], preventBubble )

    eventTypeA string containing one or more DOM event types, such as "click" or "submit," or custom event names.

    eventDataA map of data that will be passed to the event handler.

    preventBubbleSetting the third argument to false will attach a function that prevents the default action from occurring and stops the event from bubbling. The default is true.

  • version added: 1.4.bind( events )

    eventsA map of one or more DOM event types and functions to execute for them.

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().

If the eventType string contains a period (.) character, then the event is namespaced. The period character separates the event from its namespace. For example, in the call .bind('click.name', handler), the string click is the event type, and the string name is the namespace. Namespacing allows us to unbind or trigger some events of a type without affecting others. See the discussion of .unbind() for more information.

There are shorthand methods for some standard browser events such as .click() that can be used to attach or trigger event handlers. For a complete list of shorthand methods, see the events category.

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

A basic usage of .bind() is:

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

This code will cause the element with an ID of foo to respond to the click event. When a user clicks inside this element thereafter, the alert will be shown.

Multiple Events

Multiple event types can be bound at once by including each one separated by a space:

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

The effect of this on <div id="foo"> (when it does not initially have the "entered" class) is to add the "entered" class when the mouse enters the <div> and remove the class when the mouse leaves.

As of jQuery 1.4 we can bind multiple event handlers simultaneously by passing a map of event type/handler pairs:

$('#foo').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});

Event Handlers

The handler parameter takes a callback function, as shown above. Within the handler, the keyword this refers to the DOM element to which the handler is bound. To make use of the element in jQuery, it can be passed to the normal $() function. For example:

$('#foo').bind('click', function() {
  alert($(this).text());
});

After this code is executed, when the user clicks inside the element with an ID of foo, its text contents will be shown as an alert.

As of jQuery 1.4.2 duplicate event handlers can be bound to an element instead of being discarded. This is useful when the event data feature is being used, or when other unique data resides in a closure around the event handler function.

In jQuery 1.4.3 you can now pass in false in place of an event handler. This will bind an event handler equivalent to: function(){ return false; }. This function can be removed at a later time by calling: .unbind( eventName, false ).

The Event object

The handler callback function can also take parameters. When the function is called, the event object will be passed to the first parameter.

The event object is often unnecessary and the parameter omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered. However, at times it becomes necessary to gather more information about the user's environment at the time the event was initiated. View the full Event Object.

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

Using the event object in a handler looks like this:

$(document).ready(function() {
  $('#foo').bind('click', function(event) {
    alert('The mouse cursor is at ('
      + event.pageX + ', ' + event.pageY + ')');
  });
});

Note the parameter added to the anonymous function. This code will cause a click on the element with ID foo to report the page coordinates of the mouse cursor at the time of the click.

Passing Event Data

The optional eventData parameter is not commonly used. When provided, this argument allows us to pass additional information to the handler. One handy use of this parameter is to work around issues caused by closures. For example, suppose we have two event handlers that both refer to the same external variable:

var message = 'Spoon!';
$('#foo').bind('click', function() {
  alert(message);
});
message = 'Not in the face!';
$('#bar').bind('click', function() {
  alert(message);
});

Because the handlers are closures that both have message in their environment, both will display the message Not in the face! when triggered. The variable's value has changed. To sidestep this, we can pass the message in using eventData:

var message = 'Spoon!';
$('#foo').bind('click', {msg: message}, function(event) {
  alert(event.data.msg);
});
message = 'Not in the face!';
$('#bar').bind('click', {msg: message}, function(event) {
  alert(event.data.msg);
});

This time the variable is not referred to directly within the handlers; instead, the variable is passed in by value through eventData, which fixes the value at the time the event is bound. The first handler will now display Spoon! while the second will alert Not in the face!

Note that objects are passed to functions by reference, which further complicates this scenario.

If eventData is present, it is the second argument to the .bind() method; if no additional data needs to be sent to the handler, then the callback is passed as the second and final argument.

See the .trigger() method reference for a way to pass data to a handler at the time the event happens rather than when the handler is bound.

As of jQuery 1.4 we can no longer attach data (and thus, events) to object, embed, or applet elements because critical errors occur when attaching data to Java applets.

Note: Although demonstrated in the next example, it is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

Examples:

Example: Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe.

<!DOCTYPE html>
<html>
<head>
  <style>
p { background:yellow; font-weight:bold; cursor:pointer; 
padding:5px; }
p.over { background: #ccc; }
span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Click or double click here.</p>
<span></span>
<script>
$("p").bind("click", function(event){
var str = "( " + event.pageX + ", " + event.pageY + " )";
$("span").text("Click happened! " + str);
});
$("p").bind("dblclick", function(){
$("span").text("Double-click happened in " + this.nodeName);
});
$("p").bind("mouseenter mouseleave", function(event){
$(this).toggleClass("over");
});

</script>

</body>
</html>

Demo:

Example: To display each paragraph's text in an alert box whenever it is clicked:

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

Example: You can pass some extra data before the event handler:

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

Example: Cancel a default action and prevent it from bubbling up by returning false:

$("form").bind("submit", function() { return false; })

Example: Cancel only the default action by using the .preventDefault() method.

$("form").bind("submit", function(event) {
event.preventDefault();
});

Example: Stop an event from bubbling without preventing the default action by using the .stopPropagation() method.

$("form").bind("submit", function(event) {
  event.stopPropagation();
});

Example: Bind custom events.

<!DOCTYPE html>
<html>
<head>
  <style>
p { color:red; }
span { color:blue; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>Has an attached custom event.</p>
<button>Trigger custom event</button>
<span style="display:none;"></span>
<script>

$("p").bind("myCustomEvent", function(e, myName, myValue){
$(this).text(myName + ", hi there!");
$("span").stop().css("opacity", 1)
.text("myName = " + myName)
.fadeIn(30).fadeOut(1000);
});
$("button").click(function () {
$("p").trigger("myCustomEvent", [ "John" ]);
});

</script>

</body>
</html>

Demo:

Example: Bind multiple events simultaneously.

$("div.test").bind({
  click: function(){
    $(this).addClass("active");
  },
  mouseenter: function(){
    $(this).addClass("inside");
  },
  mouseleave: function(){
    $(this).removeClass("inside");
  }
});

Support and Contributions

Need help with .bind() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .bind()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://prestaul.myopenid.com/ Prestaul

    They've also added a way to specify “scope” (this is what they are calling the executing context for the callback) as an optional fourth argument. For example:

    $('#doStuff').bind('click', that.handleDoStuff, that);

    will execute handleDoStuff with “this” assigned to “that” rather than #doStuff.

  • Darrell Estabrook

    I can never remember the eventTypes. From the old jQuery documentation on bind(), possible event values are:

    blur, focus, load, resize, scroll, unload, beforeunload, click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, error, ready

  • http://macrolinz.com BlueCockatoo

    Another thing that would be good to add to this article is event name-spacing as mentioned in this article: http://www.learningjquery.com/2008/05/working-w
    and explained in this one: http://www.learningjquery.com/2007/09/namespace…

    “One way to avoid the over-reaching event unbinding is to apply a “namespace” to the click event for both binding and unbinding. So, instead of .bind('click') and .unbind('click'), we'll have, for example, .bind('click.addit') and .unbind('click.addit). “

    Not sure why that never made it into the official documentation, as it is a pretty handy feature.

  • http://twitter.com/jjmartin Jeff Martin

    a bind event that seems to be missing is ‘contextmenu’

  • Cal

    Don't forget to pass data in a map.
    I struggled to find why my events 'mouseenter' and 'mouseleave' reacted as mouseover ones.
    event.data is also used internaly by jQuery in thoses simulated events, so don't override it.

  • http://benalman.com/ "Cowboy" Ben Alman

    In case anyone is interested, the jQuery throttle / debounce plugin allows you to rate-limit callback execution by throttling or debouncing them (examples and full docs on the project page).

  • Chris

    Is there a way to prevent the duplicate binding ? having upgraded to 1.4.2 im getting duplicate click events happening wheras before my app assumed duplicate binds would replace.

  • Nicholas

    It would be nice to have a way to bind to events in the capturing phase rather than only bubbling, by adding an optional bool at the end.

  • http://th3uiguy.pip.verisignlabs.com/ th3uiguy

    An easy fix, just return false and the end of the function you bind to an event

  • Anonymous

    You mean like right-click?

  • http://stephane-klein.info/ Stéphane Klein

    I think that Wing speak about other type object, not only DOM Node object.
    In his example, someOtherObject wasn't a DOM Node.

  • http://twitter.com/jethrolarson Jethro Larson

    Yeah it might be cool to include that in core in some fashion. If nothing else so we don’t have to do our own browser hacks.

    A technique is shown here:
    http://www.quirksmode.org/js/events_properties.html

  • http://twitter.com/gijsvanzon Gijs van Zon

    Is it possible to bind a custom function on an element that is just created. So for instance:

    $('.someClass').live(function(){
    alert('element entered dom');
    });

  • Sriram

    i have a problem… I know bind accepts lot of events… But there is situation where if you add same event & same function to same object, then it is working two times.

    $('element').bind('click',myhandler);
    $('element').bind('click',myhandler);

    so myhandler called twice when i click fired. I dont say it is wrong i will tell it is not convenient.. Same object, same event, same function has to check while binding…

  • http://www.learningjquery.com/ Karl Swedberg

    One way to ensure that you don't bind the same handler twice is to unbind before you bind:

    $('element').unbind('click', myhandler).bind('click',myhandler);

  • Nevernude

    What you describe is the same as event.stopPropagation() not capturing. In the capture phase the event hasn't been delivered to the target element yet.

  • alex

    How can I replace the ‘this’ ref in the event handler with my own obj just like a call(ref,args) method?

  • theBrantMan

    Unbind all particular events by using a namespace.
    So bind like so…
    $(myelm).bind(“click.group1″, function(){dostuff;});

    and unbind all the group1 events by unbinding just the namespace.
    $(myelem).unbind(“.group1″);

    I use this in plugin development so the user can ‘reapply’ the plugin to the elements without duplicating the events.

  • theBrantMan

    Is there a way to catch an event when code changes a value of an element. the change event doesn’t fire when the .val(‘newtext’); code is run. I would like my plugin to recheck fields when the code changes field values.
    I do understand that I could just manually tell the plugin that stuff has changed, but I would like to see if there is any way the val() function can automatically tell my code.

  • Charles Merriam

    Yes, this would be grand! My current solution is watching KeyUp and Click, then binding to paste. For paste, you need to wait about 100ms for the paste value to actually change the val(): it will not change in the callback.

  • stephband

    Use jQuery.proxy, like this:

    thing.bind( 'click', jQuery.proxy( myObj, 'myObjMethod' ) );

    if the handler is a method of myObj, or:

    thing.bind( 'click', jQuery.proxy( function(e){…}, myObj ) );

    to call an arbitrary function with myObj as context.

  • http://www.google.com/profiles/hill.david.a David

    Where do I start to extend the functionality of bind to include the HTML5 dataTransfer events (dragstart, dragover, drag, drop, dragend, and etc). I would like this so I don't have to do…

    $(foobar)[0].addEventListener('dragover', function(e){
    e.preventDefault();
    }, true);

  • Robert

    Ahhh, thank you SO much. I had code where a hidden 'input' field replaced a when you clicked on the span, and then once you got a keyup: keyCode==13 in the input field, the input field would be hidden and replaced by the with the new value.

    The problem was that the input field kept firing twice on the keyup event. Your suggestion to unbind and rebind solved everything — thanks a lot!

  • http://www.facebook.com/dumb.username Steve Calderon

    Nice Tick reference!

  • http://twitter.com/halhelms Hal Helms

    You can do this:

    $( form_element ).val( 'newtext' ).trigger( 'change' )

    and that will cause a change event to occur

  • Luis Herrera

    I just download the mini version of jquery and focusout do not work! I just tried with an old version and it works, whats wrong?

  • Brian

    Can I use namespaces when I use the “event map” form of bind()? It's not working for me…

  • http://www.learningjquery.com/ Karl Swedberg

    You should be able to. Make sure you wrap them in quotes, though. Something like this should work:

    function foo(e) { console.log(e.type);};$('li').bind({  'click.bar': foo,  'mouseover.bar': foo,  'mouseout.bar': foo});
  • Ingenio Ds

    What about the rigth click?

  • Cezar Neaga

    i have something like this implemented on a website to influence the parent on a list while hovering on child. upwards class generator to help with styling.
    $('#access li ul').bind('mouseenter mouseleave', function() {
    $(this).parent().toggleClass('entered');
    });

    the problem is it generates the class on mouseenter but does not take it out on mouseleave.
    what should i do?

    thanks,
    Cezar

  • http://www.gustavelsner.com Gustav Elsner

    In case you are attaching handler to one element from multiple scripts, do not forget to call unbind('eventtype') before binding a new handler. If you don't unbind the event handler before attaching a new one, the event will call the first handler attached to the particular event. This is the case when you want to share one element with multiple scripts, E.g. sharing JQuery dialog and attaching different handlers to OK button.

  • Cezar Neaga

    i used
    $('#access li ul').unbind('mouseenter mouseleave', function() {
    $(this).parent().toggleClass('entered');
    }).bind('mouseenter mouseleave', function() {
    $(this).parent().toggleClass('entered');
    });

    as well and it didnt work also.
    Cezar

  • Basavaraj

    binding multiple event handlers simultaneously by passing a map of event type/handler pairs has some bugs…
    its showing that functions didn't have unique ID.

  • Basavaraj

    binding multiple event handlers simultaneously by passing a map of event type/handler pairs has some bugs…
    its showing that functions didn't have unique ID.

  • http://pulse.yahoo.com/_AMXXJ4GLPPMXHQLWT742UEXUPI Nirav

    HI..
    i have a function ..
    function test();
    can i bind this function to button click event using bind function.?

  • Lvance

    How to determine whether event handler is bound or not?

  • Lvance

    How to determine whether event handler is bound or not?

  • Rh Work

    Hi, can I append an event to a button, for example, there are already some events for the button, I needed to trigger my own event after them, how can I do that?
    Thank you!

  • http://twitter.com/waylybaye waylybaye

    My misstake

  • http://twitter.com/waylybaye waylybaye

    dd