Quick Reach
What is jQuery bind() method?
The bind() method of jQuery is used to bind or attach one or multiple event handlers to elements. Though from 1.7 version of jQuery, the preferred method to attach event handlers is the $.on() method.
The bind jQuery method can be used to have the same action for multiple events for the specified element.
Syntax of bind()
Following is the general syntax of using the bing method:
$(selector).bind(event,data,function)
Where:
- The selector is an element where events to be attached, like a paragraph, or Divs etc.
- Event =One or more event names like click, mouseenter, mouseleave. This is required.
- Data = data to be passed to event handler (optional)
- Function = is required
Examples of bind() method
Attaching single event
In the example below, a double click (dblclick) event is used to show an alert attached with bind() method to a Div.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#bindtest").bind("dblclick",function(){
alert("The Div is double clicked.");
});
});
</script>
</head>
<body>
<div id="bindtest">Double click to test bind method!</div>
</body>
</html>
|
Attaching multiple events example
To attach multiple events, use the space between event names. In the following example, two events i.e. mouseenter and click are used for single div with the ID=bindtest.
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function(){
$("#bindtest").bind("mouseleave click",function(){
alert("Bind method used for click and mouseleave events.");
});
});
</script>
<style>
#bindtest{
background-color:#00ffff;
width:400px;
height:50px;
border-style: solid;
border-width: 1px;
}
</style>
</head>
<body>
<div id="bindtest">Either single click or take mouse away from div!</div>
</body>
</html>
|
Read also: $.on method of jQuery
Leave A Comment?