Dan
Dan

Reputation: 1596

Link loses functionality after .appendTo is applied

When an 'a' link is appended into an HTML element it seems to become unresponsive.

http://jsfiddle.net/establish/Aqfrf/

HTML

<div class='tag-holder'>
  <span class='tag'><a href='#' class='tag-value'>Design</a></span>
</div>

<div class='tag-tray'>
</div>

jQuery

$(".tag-value").click(function() {
  $(this).parent().fadeOut("slow", function() { 
  $(this).append('<a href="#" class="tag-delete">x</a>').appendTo(".tag-tray").fadeIn("slow");      
  })
});

$(".tag-delete").click(function() {
    alert("This will be displayed only once.");
});

Upvotes: 0

Views: 92

Answers (4)

James Johnson
James Johnson

Reputation: 46047

Try this instead:

$("<a>x</a>").attr({ "href" : "#", "class" : "tag-delete" }).appendTo(".tag-tray");

Here's a jsFiddle: http://jsfiddle.net/X6Ksp/2/

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92893

Replace

$(".tag-delete").click(function()...

with

$(".tag-delete").delegate('div.tag-holder','click',function()...

Upvotes: 1

Phil
Phil

Reputation: 2307

Try using .live() instead:

$(".tag-value").live('click', function() { // ...

Upvotes: 2

Rafay
Rafay

Reputation: 31033

$(".tag-delete").live("click",function() {
    alert("This will be displayed only once.");
});

DEMO

the reason is you are appending the element dynamically to the DOM in that you have to use delegate or live

DEMO with delegate

jquery live

jquery delegate

Upvotes: 1

Related Questions