3

i have the need to add a click event to a list item i create dynamically after the DOM has loaded.

I'm using ;

$("#ListDiv li").live("click",function(event){
  do something......
 });

however when the element is loaded on the page and i click it i get nothing.

This works fine in Firefox but not in IE8. I also tried jquery livequery and deleagte but neither worked. I tried debugging with IE8 developer tools but the method is never reached

2 Answers 2

10

Use .delegate or .live and make sure you bind once the DOM is ready:

$(document).ready(function () {
    $("#ListDiv").delegate("li", "click", function (event) {
        // do something
    });
});

EDIT:

The above solution, while still perfectly valid, is now legacy/deprecated. jQuery has since introduced the .on() method:

As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers.

The implementation is quite similar to the .delegate solution posted above, but be aware that the order of parameters has changed:

$(document).ready(function () {
    $("#ListDiv").on("click", "li", function (event) {
        // do something
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

@cliveholloway - Thank you for pointing that out. I have just updated the answer :) Thanks again!
2

push your code inside document.ready

 $(document).ready(function() {
       $("#ListDiv li").live("click",function(event){
        do something......
       });
     });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.