JS mouseenter triggered twice
Asked Answered
T

4

4

The problem is about event mouseenter which is triggered twice. The code is here : http://jsfiddle.net/xyrhacom/

HTML :

<div id="elt1" class="elt" val="text1">
    text1
    <div id="elt2" class="elt" val="text2">
        text2
    <div>
</div>

JS :

$(document).ready(function() {
    $(".elt").mouseenter(function() {
        console.log($(this).attr('val'));
    });
})

I understand the problem is the event is linked to the class attribute so it is triggered for each class, but I need to find a way to consider just the event triggered for the child.

In the example, when mouseover text2, it displays in the console 'text2 text1' but I want to find a way to only display 'text2' (keeping the same HTML code)

Terribly answered 3/10, 2014 at 12:45 Comment(0)
R
4

use stopPropagation(); Prevents the event from bubbling up the DOM tree,

$(document).ready(function() {
    $(".elt").mouseenter(function(e) {
       e.stopPropagation();
        console.log($(this).attr('val'));
    });
})

Updated demo

Reunion answered 3/10, 2014 at 12:47 Comment(1)
I don't know if things were different when this question was answered but 'mouseenter' does NOT bubble at all as per MDN documentation in 2021.Quilting
S
1

Both #elt1 and #elt2 have your selector class (.elt ) use event.stopPropagation() to stop event from bubbling up in the DOM tree

$(document).ready(function() {
    $(".elt").mouseenter(function(event) {
        event.stopPropagation();
        console.log($(this).attr('val'));
    });
})
Sicilia answered 3/10, 2014 at 12:49 Comment(0)
J
1

If you only want to let the first child trigger the event, you can use a selector like:

$(".elt > .elt")
Jar answered 3/10, 2014 at 12:49 Comment(0)
G
1

The issue here is that elt2 is inside elt1, and the mouseenter event is bubbling up the DOM chain. You need to stop the bubbling by using event.stopPropagation() to prevent your function from firing multiple times:

$(document).ready(function() {
    $(".elt").mouseenter(function(e) {
        e.stopPropagation();

        console.log($(this).attr('val'));
    });
})

I've made a fiddle here: http://jsfiddle.net/autoboxer/9e243sgL/

Cheers, autoboxer

Glider answered 3/10, 2014 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.