FadeOut and Remove Table Row

Nick Olsen picture Nick Olsen · Aug 29, 2011 · Viewed 17.6k times · Source

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?

Answer

Diodeus - James MacFarlane picture Diodeus - James MacFarlane · Aug 29, 2011

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