0

I've seen a few different solutions but I can't seem to make them work. The solution I attempted is based on this question:jQuery hover not working with dynamic elements. I'm not seeing a distinguishable difference between the answer provided for that question and my own.

Here's the link for the jsfiddle that they used also: http://jsfiddle.net/qgTzE/4/

Dynamically created element:

<div class="deckCardListCard floatRight ui-corner-all" data-cardID="190563" id="1">190563</div>

Javascript to add hover:

        $(".deckCardListCard").on({
            mouseenter: function() {
                $("#deckCardDisplay").css("background-image", "url('images/cards/" + $(this).attr("data-cardID") + ".png')");
            },
            mouseleave: function() {
                $("#deckCardDisplay").css("background-image", "url('images/layout/back.png')");
            }
        });

** EDIT **

I have selected an answer from below but the question is more why what I have doesn't work when the apparent same thing works here: jQuery hover not working with dynamic elements

Community
  • 1
  • 1
Styles2304
  • 143
  • 1
  • 14
  • you're targeting ` $("#deckCardDisplay")` but the `id` in dynamically generated div that you mention is "1" are you sure you're not missing something here. – vendettamit Oct 01 '15 at 15:16
  • yes, #deckCardDisplay is a static div that shows the image of the card when hovering over the dynamically created .deckCardListCard. – Styles2304 Oct 01 '15 at 15:32

3 Answers3

1

Use it like this for event delegation from existing parent element or document or body: you read about it here

$(document).on("mouseenter", ".deckCardListCard", function(){
     $("#deckCardDisplay").css("background-image", "url('images/cards/" + $(this).attr("data-cardID") + ".png')");
}).on("mouseleave", ".deckCardListCard", function(){
     $("#deckCardDisplay").css("background-image", "url('images/layout/back.png')");
});
SSA
  • 5,433
  • 4
  • 36
  • 50
  • I still don't understand why what I have doesn't work. I've seen the solution you provided in other places but the solution from http://stackoverflow.com/questions/22180546/jquery-hover-not-working-with-dynamic-elements Seems to be exactly what I've done. Either way, thank you. – Styles2304 Oct 01 '15 at 16:06
0

Assuming you have a parent element/container, you should target that:

assume this:

<div id="parent"> ... your dynamic elements here ... </div>

Then use something like

$('#parent').on('.deckCardListCard', 'mouseenter', function(){});
Yeronimo
  • 1,731
  • 15
  • 28
0

The way to delegate these events is to pass selector param and bind event to static parent container:

$('#link_delete_holder').on({
     mouseenter: function () {
         $(this).attr('src', 'http://placehold.it/250x150');
     },
     mouseleave: function () {
         $(this).attr('src', 'http://placehold.it/150x150');
     }
 }, '.link_delete');

-DEMO-

A. Wolff
  • 74,033
  • 9
  • 94
  • 155