The jQuery bind() event is used to attach one or more event handlers for selected elements from a set of elements. It specifies a function to run when the event occurs.
It is generally used together with other events of jQuery.
Syntax:
$(selector).bind(event,data,function,map)
Parameter | Description |
---|---|
Event | It is a mandatory parameter. It specifies one or more events to attach to the elements. If you want to add multiple events they they must be separated by space. |
Data | It is an optional parameter. It specifies additional data to pass along to the function. |
Function | It is a mandatory parameter. It executes the function to run when the event occurs. |
Map | It specifies an event map which contains one or more events or functions attached to the element. |
Let's take an example to demonstrate jQuery bind() event.
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").bind("click", function(){ alert("This paragraph was clicked."); }); }); </script> </head> <body> <p>Click on the statement.</p> </body> </html>
Output:
Click on the statement.
Let's take an example of jQuery bind() with mouseenter() and mouseleave() events.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>bind demo</title> <style> p { background: yellow; font-weight: bold; cursor: pointer; padding: 5px; } p.over { background: #ccc; } span { color: red; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <p>Click or double click on the statement.</p> <span></span> <script> $( "p" ).bind( "click", function( event ) { var str = "( " + event.pageX + ", " + event.pageY + " )"; $( "span" ).text( "This is a single click! " + str ); }); $( "p" ).bind( "dblclick", function() { $( "span" ).text( "This is a double click on " + this.nodeName ); }); $( "p" ).bind( "mouseenter mouseleave", function( event ) { $( this ).toggleClass( "over" ); }); </script> </body> </html>