Knowledge Walls
Venkatesan
Hyderabad, Andhra Pradesh, India
Passcode:
.on() in Event handler methods of JQuery
2062 Views
on() method is always alive to the selectors till end. which means if creating event directly with element like $(selector).click(function{}); then when user creating multiple elements dynamically on the same page has to apply click event again on the selector element. Event created with on() method then automatically creates the events for new elements with are dynamically get inserted on the page.

$("ul.menu li").click(function(){
    document.location = $(this).attr("loc");
});

instead of

$("ul.menu").on("click","li",function(){
     document.location = $(this).attr("loc");
});

If any new <li> element is inserts on <ul> then on() method automatically assigns the click event to the new <li> element. live() and delegate() methods are deprecated method of on() method.
Example of .on() method
<script type="text/javascript">
$(function(){
    $("ul").on("click","li",function(){
         alert($(this).html());
    });

    $("button").click(function(){
         $("ul").append("<li>"+($("ul li").length+1)+"</li>");
    });
});
</script>

Click on the &lt;li&gt; tag and button
<ul>
   <li>1</li>
   <li>2</li>
</ul>

<button>INSERT &lt;LI&gt;</button>
Demo link 
Previous Topics
Previous lessons of current book.
Jquery Exercises of JQuery
HTML Form of JQuery
HTML Insertion of JQuery
Best Lessons of "JQuery"
Top lessons which are viewed more times.
HTML Insertion of JQuery
HTML Insertion of JQuery
HTML Insertion of JQuery
HTML Insertion of JQuery
Form Validation of JQuery
HTML Form of JQuery
HTML Insertion of JQuery
HTML Insertion of JQuery
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details