dionysosz
dionysosz

Reputation: 163

jQuery not working for new items

Hello I want to hide/show the rows of a table on hover. The problem is that query is not working on newly dynamically added elements..

<button id="myButton">Add New Row</button>
<br/>
<br/>

<br/>
<table id="myTable">
    <tr>
        <td>This is a static row.</td>
    </tr>
</table>



$("#myButton").click(function () {

   var newRow = '<tr><td>This is a dynamically added row.</td></tr>'; 
    $('#myTable').append(newRow);
});



 $('#myTable tr').hover(

       function() {
       $(this).animate({opacity: 0}, 1);

     },
     function() {

         $(this).animate({opacity: 1}, 1);
     }

    );

here is an example: link

Upvotes: 0

Views: 51

Answers (4)

Ben Creasy
Ben Creasy

Reputation: 4136

You may want to consider using a CSS3 transition for something like this. Simply add this to your CSS:

#myTable tr:hover {
    opacity: 0;
    transition: opacity 0.2s ease;
}

CSS is likely faster. See Myth Busting: CSS Animations vs. JavaScript for an overview of the pros/cons.

Upvotes: 1

user4297937
user4297937

Reputation:

You should be using something like this:

$(staticAncestors).on(eventName, dynamicChild, function() {});

Here's how it's applied in your code:

$("#myButton").click(function () {

   var newRow = '<tr><td>This is a dynamically added row.</td></tr>'; 
    $('#myTable').append(newRow);
});

$('#myTable').on( "mouseover", "tr", function () {
    $(this).animate({opacity: 0}, 1);
});

$('#myTable').on( "mouseout", "tr", function () {
    $(this).animate({opacity: 1}, 1);
});

JSFiddle: http://jsfiddle.net/Lfuugkw2/3/

Upvotes: 2

brroshan
brroshan

Reputation: 1650

Try event delegation:

 $(document).on("mouseenter", "#myTable tr", function(){
         $(this).animate({opacity: 0}, 1);
 });

 $(document).on("mouseleave", "#myTable tr", function(){
         $(this).animate({opacity: 1}, 1);
 });

Understanding Event Delegation

Upvotes: 2

Flobin
Flobin

Reputation: 708

To use a 'live' selection, use .on().

So like this:

$('body').on({
    mouseenter: function() {
        $( this ).animate({opacity: 0}, 1);
    }, mouseleave: function() {
        $( this ).animate({opacity: 1}, 1);
    }
},'#myTable tr');

Upvotes: 2

Related Questions