.on()

In this chapter you will learn:

  1. on() binds event handlers
  2. bind target element with event handler
  3. bind events to generic elements

on() binds event handlers

.on() replaces the functionality of all the event methods.

<html> <!-- j a  v  a  2 s  .  c  o  m-->
    <head>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
        <script> 
            $(function(){ 
                $("#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>

Click to view the demo

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> <!--  j  a v  a 2 s.  com-->
    <head>
        <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
        <script>
            $(function(){ 
                $(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>

Click to view the demo

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!

Next chapter...

What you will learn in the next chapter:

  1. Syntax and Description for .one() event method
  2. How to bind click event once
  3. How to execute an event only once
  4. How to only handler click event once
Home » jQuery » 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()
.on()
.one()
.ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()