tags:

views:

140

answers:

3

I'm currently using the following code to append a X link to each element on rollover.

$(".item").hover(function() {
    var id = $(this).attr("id");

    var roll = $('<a class="close" href="#">X</a>').hide();

    roll.prependTo($(this)).fadeIn(0);
}, function() {
    $(this).find("a:first").fadeOut(0, function() {
     $(this).remove()
    });
});

What I am unable to code up is the ability for when this X link is pressed, it removes the parent div it is currently in.

Would love help on this :)

+3  A: 

Well, firstly I would suggest that dynamically adding and removing elements on a hover() event could be problematic. The usual solution is to show/hide them as appropriate. It's far more performant too.

So:

<div class="item">
  <p>Some content</p>
  <a class="close" href="#">X</a>
</div>

and

div.item a.close { display: none; }

and

$("div.item").hover(function() {
  $("a.close", this).fadeIn();
}, function() {
  $("a.close", this).fadeOut();
});
$("a.close").click(function() {
  $(this).parents("div.item:first").remove();
  return false;
});

Now you can do this by dynamically adding the link to the DOM but I would advise against it. If you do however, use live() for the event handling:

$("a.close").live("click", function() {
  $(this).parents("div.item:first").remove();
});
cletus
you're applying the display none to the wrong element. I think you meant to apply it to the anchor tag
TStamper
Qutie right, thanks.
cletus
Amazing, thank you very much.
James
+1  A: 

Something like this should work. Although as cletus said what you're doing on a hover() can be problematic.

$("a.close").click(function(){
   $(this).parent().remove();
});
fmsf
+1  A: 

Combining all the other stuff with a click handler:

$('<a class="close" href="#">X</a>')
      .hide()
      .prependTo($(this))
      .click( function() { $(this).closest('div').remove(); })
      .fadeTo(0);
tvanfosson