Tuesday, January 13, 2015

Jquery Best practice - Event Handling

  We usually do this :

$("#longlist li").on("mouseenter", function() {

    $(this).text("Click me!");

  });


  $("#longlist li").on("click", function() {

    $(this).text("Why did you click me?!");

  });

This is fine IF...

If you like using a lot of memory for event handlers
If you don't have many DOM elements
If you don't care about best practices


Best Approach : Event Delegation 


var list = $("#longlist");

  list.on("mouseenter", "li", function(){

    $(this).text("Click me!");

  });

  list.on("click", "li", function() {

    $(this).text("Why did you click me?!");

  });

Simple but thoughtful :)

Try n feel the difference...

No comments:

Post a Comment