0

When classes are present at page rendering time, the following code works:

$().ready(function () {

    $(".productzoom").on('hover click', function () {//also add this function to click
        $(this).closest(".product1").find(".image span").css('top', $(this).position().top - 200);
        $(this).closest(".product1").find(".image span").css('left', $(this).position().left + 20);
    });
});

However, later I'm inserting content dynamically, the above code seems not to work anymore when I hover or click over the .productzoom class. I thought by using .on jQuery would attach the hook also on newly inserted elements, but it doesn't...why?

Adam
  • 6,041
  • 36
  • 120
  • 208
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – kalley Nov 08 '13 at 02:39

2 Answers2

2

As per jquery .on() doc, 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(). 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, so you need to do:

$(document).on('hover click', '.productzoom', function () {//also add this function to click
     $(this).closest(".product1").find(".image span").css('top', $(this).position().top - 200);
     $(this).closest(".product1").find(".image span").css('left', $(this).position().left + 20);
});
Sudhir Bastakoti
  • 99,167
  • 15
  • 158
  • 162
1

Since you are dealing with dynamic elements, you need to make use of event delegation... for that the syntax of .on() is slightly different

The event delegation syntax is $(<staticelement>).on(event, <dynamic target selector>, handler)

$(document).on('hover click', ".productzoom", function () { //also add this function to click
    $(this).closest(".product1").find(".image span").css('top', $(this).position().top - 200);
    $(this).closest(".product1").find(".image span").css('left', $(this).position().left + 20);
});

Your code can be changed to a much better format like

$(document).on('hover click', ".productzoom", function () { //also add this function to click
    var position = $(this).position();
    $(this).closest(".product1").find(".image span").css({
        'top': position.top - 200,
        'left': position.left + 20
    });
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531