Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS mouseenter triggered twice

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)

like image 924
user3656665 Avatar asked Mar 19 '23 07:03

user3656665


1 Answers

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

like image 122
Balachandran Avatar answered Mar 31 '23 03:03

Balachandran