.on()
on() binds event handlers
.on()
replaces the functionality of all the event methods.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script>
$(function(){ <!--from w w w . jav a 2 s. c om-->
$("#aDiv").on('click', function(){
document.writeln("Handler 1");
});
$("#aDiv").on('click', function(){
document.writeln("Handler 2");
});
});
</script>
</head>
<body>
<div id="aDiv" class="boxDiv">Press Me java2s.com
</div>
</body>
</html>
The code above generates the following result.
bind target element with event handler
To use .on()
like
delegate()
or .live()
,
add a second, optional selector argument representing
the target element for the event.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script>
$(function(){ <!--from w ww . j a v a 2s. c o m-->
$(document).on("click", "#anchor", function(event){
document.writeln("I have a handler");
});
$("body").append("<a id='anchor'> I go no where </a>")
});
</script>
</head>
<body>
</body>
</html>
The code above generates the following result.
bind events to generic elements
To bind events to generic elements across
the whole page, you use .on()
on
the document and pass in your generic p
or a selector.
Hit Me!
Javascript Tutorial Event
Event
Event attributes
event.keycode
event.clientX/clientY
pageX/pageY
Cancel event
Event target
bind
.blur()
.change()
.click()
.error()
.dblclick()
.delegate()
.die()
.focus()
.hover()
.keydown()
.keypress()
.keyup()
.live()
.load()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseover()
.mouseout()
.mouseup()
.off()
.ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()
Event
Event attributes
event.keycode
event.clientX/clientY
pageX/pageY
Cancel event
Event target
bind
.blur()
.change()
.click()
.error()
.dblclick()
.delegate()
.die()
.focus()
.hover()
.keydown()
.keypress()
.keyup()
.live()
.load()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseover()
.mouseout()
.mouseup()
.off()
.on()
.one().ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()