jQuery > Events

Attach & detach multiple events in jQuery

How to attach multiple events at once to an element in jQuery?


To attach or detach a single event to a html element, we read this.

To attach or detach multiple events to an element, write the events in bind and unbind method separated by blank space.

   <script>
       function bindAction() {
           alert("I am active !");
       }

       $("#btnBindAction").click(function () {
           $("#btnAction").bind('mouseenter click', bindAction).val("Mouse hover Now and then click");
       });

       $("#btnUnbindAction").click(function () {
           $("#btnAction").unbind('mouseenter click', bindAction).val("Simple button");
       });
  </script>

In the above code, when we click on the “btnBindAction” (id value of an html) button, mouseenter as well as click event is attached to the button whose id is "btnAction". So when we try to mouse hover the "btnAction" button we get the JavaScript alert ("I am active !"). Now when we click on this button and we again get alert because of click event.

Clicking "btnUnbindAction" (id value of the html) button, unbinds both mouseover and click events from the button"btnAction".

 Views: 2041 | Post Order: 65



Write for us