James
James

Reputation: 6008

Remove element with JQuery

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

Upvotes: 0

Views: 462

Answers (3)

cletus
cletus

Reputation: 625077

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

Upvotes: 3

tvanfosson
tvanfosson

Reputation: 532465

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

Upvotes: 1

fmsf
fmsf

Reputation: 37137

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

Upvotes: 1

Related Questions