0

I am creating some elements and appending it, and its working fine but when I want to call any function or want to call any jquery that not work, but when i put that elements directly instead of appending then it works properly. In all to say that appending element does not call any function or anything.

JQUERY CODE:

var cart_content = jQuery($.create('li', {}, [])).append($.create('span',{}, [av_title]),$.create('img', {"src":"images/delete_icon.png", "class":"cart_content", "alt":"delete", "title":"Delete"}, []));
$(".advertise_cart").append(cart_content);


$(".cart_content").click(function(){    alert("Hello"); });
<ul class="advertise_cart" id="advertise_cart_id">
   <li>
        <span>Inner Content 1</span>
        <img src="images/delete_icon.png" class="cart_content" alt="delete" title="Delete">    <!------ On clicking on this will show alert box, but on clicking on appended element will not call alert box or anything ----->
    </li>
</ul>

Thanks in advance

1
  • 1
    live() and delegate() best, if it works for you why can't you accept it as answers. Sep 5, 2011 at 11:22

4 Answers 4

1

The problem you're experiencing is the result of the elements not being present in the DOM when the events are bound. To work around this, you can use delegate() or live():

$('body').delegate('.cart_content','click',
    function(){
        alert('hello');
    });

JS Fiddle demo.

References:

1
  • You're very welcome! =) (Please consider up-voting, or accepting, the answer(s) that you feel were helpful in solving your problem). Sep 5, 2011 at 11:18
1

Do not use .click function.

Use live function it work for newly added element in DOM

like this :

$(".cart_content").live(function(){    alert("Hello"); });
2
  • thanks for your reply, but can you tell me how should i use click event in this. Sep 5, 2011 at 11:18
  • $(".cart_content").live('click',function(){ alert("Hello"); }); api.jquery.com/live Sep 5, 2011 at 11:25
0

Using the live function to handle your event might help.

0

The only thing I'd add is that the live function means that the handler will continue to be applied to content that matches the selector at any point in the future (until and unless you call unbind). That is probably what you want here. If it isn't, you could write could that would add the click handler after a brief delay (say, 1.5 seconds). Or to be a little more sure, you could write code that would check for the presence of .cart_content every 100 milliseconds until it's found, and then add the click handler. So this approach would add the click handler only once. If something caused another .cart_content were added later, the click handler would not automatically be added.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.