bind
In this chapter you will learn:
- Syntax for bind method
- How to bind the same action twice
- How to bind double click event
- How to bind mouse enter/leave event
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><!-- ja va 2 s. c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("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> <!-- j a va2s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script>
$(function(){
$("#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><!--from j a v a 2 s .co m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("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><!--from java2s . co m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("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>
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for blur event
- How to blue user input
- How to use blur event to change the style for the next element