Question

I am trying to use .on(), since .live() is deprecated. Yet I can't get .on() to work.

I got this html part:

...
<div class="tile" data-position="0,0" style="top: 539.5px; left: 380px;">
    <div class="content">
        <div class="image"><img src="bla.png" alt="" /></div>
        <div class="title">title1</div>
    </div>
</div>

<div class="tile" data-position="0,1" style="top: 539.5px; left: 380px;">
    <div class="content">
        <div class="image"><img src="bla.png" alt="" /></div>
        <div class="title">title2</div>
    </div>
</div>

<div class="tile" data-position="0,2" style="top: 539.5px; left: 380px;">
    <div class="content">
        <div class="image"><img src="bla.png" alt="" /></div>
        <div class="title">title3</div>
    </div>
</div>
...

and this jQuery:

$('.tile').on({
    mouseenter: function()
    {
        alert("enter");
        $(this).find('.content .image').animate({
            opacity: 0.5
        }, 100);
    },
    mouseleave: function()
    {
        alert("leave");
    }
});

No matter what syntax I use from the documentation from Jquery, it doesn't work. Does any know what went wrong here? This syntax should work, it is pretty the same as in an example at jQuery.

Was it helpful?

Solution

Drop those in a <script> tag at the bottom of <body>. This will ensure that the elements you're attaching these handlers do actually exist.

<script>
$('.tile').on({
    mouseenter: function()
    {
        alert("enter");
        $(this).find('.content .image').animate({
            opacity: 0.5
        }, 100);
    },
    mouseleave: function()
    {
        alert("leave");
    }
});
</script>
</body>

Or you could use DOM ready handler which will execute these events after DOM is loaded fully and all elements are available.

$(function() {
    $('.tile').on({
        mouseenter: function()
        {
            alert("enter");
            $(this).find('.content .image').animate({
                opacity: 0.5
            }, 100);
        },
        mouseleave: function()
        {
            alert("leave");
        }
    });
});

Or let the omnipresent document object delegate the event to .tiles:

$(document).on({
    mouseenter: function()
    {
        alert("enter");
        $(this).find('.content .image').animate({
            opacity: 0.5
        }, 100);
    },
    mouseleave: function()
    {
        alert("leave");
    }
},'.tile');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top