How to bind event with jQuery
Syntax
.bind(eventType[, eventData], handler)
attaches a handler to an event for the elements. It has the following parameters.
eventType
A string containing one or more JavaScript event types such as click, submit, or custom event nameseventData (optional)
A map of data passed to the event handlerhandler
>
A function to execute
.bind(eventType[, eventData], handler)
returns the
jQuery object, for chaining purposes.
For example, to bind a mouseover event:
$("#objId").bind('mouseover', function(event){
// code here...
});
jQuery also has method shortcuts for creating event handlers.
$("#el").bind('click', function(event){
// do stuff
});
can be rewritten as:
$("#el).click(function(event){
// do stuff
});
The following code binds the click event.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from ww w. j a v a2 s . co m-->
$("h1").bind("click", function(e){
var str = "( " + e.pageX + ", " + e.pageY + " )";
$("h1").text("Click happened! " + str);
});
});
</script>
</head>
<body>
<body>
<div><h1>header 1</h1></div>
</body>
</html>
bind the same action twice
The following code binds the click action twice.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script>
$(function(){ <!-- w w w . ja va 2s . co m-->
$("#aDiv").bind('click', function(){
document.writeln("Handler 1");
});
$("#aDiv").bind('click', function(){
document.writeln("Handler 2");
});
});
</script>
</head>
<body>
<div id="aDiv" class="boxDiv">Press java2s.com
</div>
</body>
</html>
Bind double click event
The following code binds double click event to header.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- w w w . java 2 s. c o m-->
$("h1").bind("dblclick", function(e){
var str = "( " + e.pageX + ", " + e.pageY + " )";
$("h1").text("Click happened! " + str);
});
});
</script>
</head>
<body>
<body>
<div><h1>j a v a2s.com</h1></div>
</body>
</html>
Bind mouse enter/leave event
The following code binds mouse enter event. It outputs the mouse position in the event handler.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- www.j ava2 s. c o m-->
$("h1").bind("mouseenter mouseleave", function(e){
var str = "( " + e.pageX + ", " + e.pageY + " )";
$("h1").text("Click happened! " + str);
});
});
</script>
</head>
<body>
<body>
<div><h1>header 1</h1></div>
</body>
</html>