jQuery .on() event methods

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

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!





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities