I have a simple set of jQuery statements for a particular class:
$(".printersToggle").mouseover(function() {
$(this).addClass("printersToggleOver");
});
$(".printersToggle").mouseout(function() {
$(this).removeClass("printersToggleOver");
});
and:
$(".printersToggle").click(function() {
var id = $(this).attr('id');
$.getJSON("/ajax",
function(data) {
$.each(data, function(key, val) {
$("#" + id).replaceWith('<div class="row printersToggle" id="' + id '"><div class="twelve columns">Show printers (Best price: £4.65)</div></div><!-- end of printers toggle --><!-- printers --><div class="row" id="printers"><table><thead><tr><th>Title</th><th>Rating (%)</th><th>Experience (jobs)</th><th>Average job speed (days)</th><th>Reliability (%)</th><th>Cost</th><th>Print</th></tr></thead><tbody><tr><td id="printersName_{{ design.id }}"></td><td id="printersRating"></td><td>4</td><td>2</td><td>96</td><td>£4.56</td><td class="success printButton radius">Add to Cart</td></tr></tbody></table></div>');
});
});
});
});
Without the second one (the click function), the first works as intended. With the second statement, the mouseover effects stop working. Any idea what’s going on here?
When you call replaceWith(), you are removing the previous DOM element along with any event handlers associated with it. You should use on() with a selector to bind the event handler dynamically: