jQuery mouseenter() is not firing

August picture August · Apr 29, 2013 · Viewed 8k times · Source

So I have this simple HTML

<div class="song">
    <img src="http://o.scdn.co/300/40e3ec60c92513f724f47ce71baad1e496627107">
</div>

And this simple jQuery

$(".song").on( "mouseenter", function() {
    $(this).css( "background-color", "red" );
    alert('bla');
});

And the event does not fire.

Although

$(".naujienuKategorija").on( "mouseenter", function() {
    $(this).css( "background-color", "red" );
});

Works just fine on

<p class="naujienuKategorija">Apklausa</p>

Which is on the same page.

.song has the following css

.song {
    padding-bottom: 12px;
    margin-bottom: 15px;
    border-bottom: 1px solid #E0E0E0;
    overflow: hidden;
}

I am obviously missing something... obvious.

Answer

Ian picture Ian · Apr 29, 2013

In order for an event to be bound to an element, the element has to be ready and found. A general way to do this is to put your event bindings inside of $(document).ready because it ensures original elements on the page can be accessed. So use this:

$(document).ready(function () {
    $(".song").on( "mouseenter", function() {
        $(this).css( "background-color", "red" );
        alert('bla');
    });
});

Another option is to put your event binding on the page at any time after the target elements, either immediately or right before the </body>. For example:

<div class="song"></div>
<div class="song></div>

<script type="text/javascript">
    $(".song").on("mouseenter", function () {

    });
</script>

It might've been working with the .naujienuKategorija elements because you were using the second method above, but weren't with the .song elements.