Reputation: 163
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
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
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
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