Santiago
Santiago

Reputation: 2455

What's the best way to append html just once?

I want to open a Div and append the Facebook comments box when I click on a "Show comments" link. But I want to append the FB-Comments just once, and then just use the link to toggle that Div.

I was trying something like this but it just appends it every time I click on the link, of course...

http://jsfiddle.net/4LnzD/

Thanks!!

UPDATE:

http://jsfiddle.net/4LnzD/4/

Now it's working great, but if someone knows a most efficient way to do it, you're welcome!

Upvotes: 0

Views: 2122

Answers (3)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

Add a class name to the target element after adding the content. Check for the existence of the class name before adding it a second time.

1) add the class

$('#target').addClass("done")

2) check for the class

if($('#target').hasClass("done")) {
 ...
}

Upvotes: 3

thebiffboff
thebiffboff

Reputation: 958

Check to see if the comments div already exists in the DOM, if it doesn't then append:

if( ! $('#fb_comments_' + uid).children(".fb-comments").length ){
  $('#fb_comments_' + uid).append(commentBox);
}

$('#fb_comments_' + uid).toggle();

.length will return the number of instances of elements that match that selector in the DOM. As 0 is equivalent to false in javascript, we can treat it as a boolean in the conditional.

Upvotes: 1

SomeKittens
SomeKittens

Reputation: 39522

Use:

$(document).load( function() {
    //Load comments section here
    $('.fb_comments').hide(); 
})

This will create the comments, but then hide them. Then create the button, and onClick (or bind a .click()) call this:

$('.fb_comments').toggle(); 

Upvotes: 0

Related Questions