I have a simple Jquery script which populates an empty table with lots of rows and cells.
Depending on the state of a checkbox I want to toggle a CSS class for all cells within the newly populated table (not there when the page loads, but dynamically created by a JS function upon a form submit).
I am able to set up a “click” event on the table cells and it works fine.
But my attempts at using on() to bind a function to a hover() event have not been successful. The event never seems to get triggered and no console log message produced. Any ideas about what I’m doing wrong?
$("#resultTable").click(function(e){ // This function works fine.
$(e.target).closest('td').toggleClass('stay');
});
$("#resultTable td").on("hover", //Same problem for a simpler 'mouseover'
function(event){
console.log("MOUSE OVER"); //Never appears
$(this).toggleClass('over');
},
function(event){
console.log("MOUSE OUT"); //Never appears
$(this).toggleClass('over');
}
);
If you are dynamically inserting rows into the table then
.onwill not work if its binded to the tds that come into existence after the binding happens. From the docs When the call to.onis made the element to which the event is binded must exist in the DOM when the binding happens.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().
This might work
If you are only adding the rows dynamically then you can attach the event to
#resultTableto make the delegation a bit faster.