armonge
armonge

Reputation: 3138

How to correctly use jQuery remove in this case

I have the following fiddle http://jsfiddle.net/ycysD/1/ in which i try to remove an element of the DOM using a funcion, also I have two events that execute this function, both do the same thing however in one casi it fails

Sorry for the english and tell me if you need some other information

Upvotes: 4

Views: 84

Answers (2)

amosrivera
amosrivera

Reputation: 26514

The behavior is caused by a conflict in the code. When the close button is clicked you both create and remove a new .media-list-display.

 _close.bind('click',function(e){
//This line removes the .media-list-display div when 
//the close button is clicked

$('.media-list a').live('click',function(e){
//This line adds a new .media-list-display div when any `<a>` 
//inside .media-list is clicked.

The problem is that the close button is also an <a> inside .media-list so when it is clicked it triggers both events creating an endless loop of removing and creating.

Check this link out with alerts on the conflicting parts.

Upvotes: 0

Blender
Blender

Reputation: 298166

No idea if this is the correct behavior, but here's what I changed:

function closeMediaList(what){
    $('.media-list-display').fadeOut(function(){
        what.remove();
    });
};

what is the object which gets removed, so instead of just calling:

closeMedialList();

You call:

closeMediaList($(this));

Here's a demo of what the changes did: http://jsfiddle.net/t4u33/

Upvotes: 3

Related Questions