I’m trying to use jQuery’s hover() to change the background color any TR that you mouse over, and I also use a click() to move a TR between tables. But once I move the TR to another table, hover() and click() don’t work.
Can someone tell me why? And how I can fix this? Here’s my code: http://jsfiddle.net/MJNGL/
$(document).ready(function() {
$("table tr").hover(
function() {
$(this).css('background', 'yellow');
},
function () {
$(this).css('background', '');
}
)
$("table tr").click(function () {
var id = $(this).children().attr("id");
$(".cityItem1").each(function m(x,e) {
if ($(e).children().attr("id") == id) {
$(e).remove();
$("#tblCity2").append('<tr class="tableRow"><td width="750" id="' + $(e).children().attr('id') + '">' + $(e).children().html() + '</td></tr>');
}
});
});
});
Try changing the hover function like below,
DEMO
Why your code didn’t work?
The event handlers are bound to the elements that are available in DOM. In your case, onPageLoad
$('table tr')– returns 2 matchingtrs that are currently there in DOM and so thehoverandclickevent are bound only to those twotrs.Later on
clickon thetryou remove the row from the table and append it to table 2. At this point you have to re-bind the handler again to the newly added row. But that is a painful process to bind the handler every time you add a row.So we have an alternate interesting approach called event-delegation.
Direct and delegated events
The majority of browser events bubble, or propagate, from the deepest, innermost element (the event target) in the document where they occur all the way up to the body and the document element.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.
~ From jQuery doc http://api.jquery.com/on/