Page 1 of 1

Append element problem

Posted: Mon Sep 05, 2011 5:51 am
by dheeraja
Hello guys,

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:

Code: Select all

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);

Code: Select all

$(".cart_content").click(function(){
	alert("Hello");
});
HTML CODE:

Code: Select all

<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

Re: Append element problem

Posted: Thu Sep 08, 2011 11:25 pm
by KCAstroTech
If I am understanding you correctly the first JavaScript code appends the elements on the page as it is supposed to, but the click event doesn't work. Yet when you manually put the elements on the page the click events work. Is that correct?

If that is correct then it would appear that the elements were not yet on the page at the time the click event script was called and thus no events were bound. To make sure that the elements are appended prior to adding the click events, I recommend that you do something like this:

Code: Select all

$(document).ready(function() {
var cart_content = $($.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).find(".cart_content").click(function(){
        alert("Hello");
});
});
This way once the page is ready it calls the .ready() function which then creates the elements, then it appends them in the target element, then it finds all of the elements in the target element with the "advertise_cart" class and adds the click event. Also, I'm not sure what this $.create() function is but it would seem to me faster and easier to use:

Code: Select all

 var cart_content = $('<li><span>'+av_title+'</span><img src="images/delete_icon.png" class="cart_content" alt="delete" title="Delete" /></li>');
Hope this helps!