Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FadeOut and Remove Table Row

I know this question has been asked before but I seem to have a different problem than has been addressed before. I have a table and I would like each row to have a delete link that fades the table row out and then removes the table row from the DOM. My first problem was that I couldn't get the jQuery fadeOut effect to work on table rows and found that you have to actually call fadeOut on the row's td elements. So, here is my jJavascript:

$('span.deleteItem').live('click', function() {  
    $(this).closest('tr').find('td').fadeOut('fast', 
        function(){ 
            $(this).parents('tr:first').remove();                    
        });    

    return false;
});

The span element lives inside a td so I find the closest tr element when it is clicked, and then fall the fadeOut function on each of its td elements. This works great.

The problem is that in the callback function, 'this' is actually referencing the window element not the individual td element that was hidden. From my understanding 'this' was supposed to reference the element that was faded out.

Any ideas?

like image 911
Nick Olsen Avatar asked Aug 29 '11 18:08

Nick Olsen


2 Answers

Grab the "this" reference and pass it on:

$('span.deleteItem').live('click', function() {  
    var here = this;
    $(this).closest('tr').find('td').fadeOut('fast', 
        function(here){ 
            $(here).parents('tr:first').remove();                    
        });    

    return false;
});
like image 150
Diodeus - James MacFarlane Avatar answered Nov 19 '22 15:11

Diodeus - James MacFarlane


I think this is what you are looking for:

$('span.deleteItem').live('click', function() { 
    var tableRow = $(this).closest('tr');
    tableRow.find('td').fadeOut('fast', 
        function(){ 
            tableRow.remove();                    
        }
    );
});

EDIT: I think Opatut is right, as show in his jsFiddle.

like image 5
Struikel Avatar answered Nov 19 '22 16:11

Struikel