Reputation: 2824
I made this simple code to understand how it works:
<div title="1">
one
<p title="2">two</p>
</div>
<br />
<div id="result"></div>
<script src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
//$("body").on("mouseover","*",function(){
//$("body").on("mouseenter","*",function(){
var html = $(this).attr("title");
console.log(html);
$("#result").text(html);
//});
});
</script>
When I use mouseover
, the problem is that when I point to two
, the event listener will first fire on two
and then on one
, so the effect will be like I pointed to one
.
On the other hand, if I use mouseenter
, the problem appears if I point to two
without pointing to one
, the effect will be one
.
And if I point to one
, then to two
, and then to one
again, there will be no effect at all because two
is part of one
so js sees that I'm still in one
and won't work.
Is there any solution to this ?
Upvotes: 0
Views: 133
Reputation: 288680
Basically, the difference between mouseover
and mouseenter
is
Similar to
mouseover
,mouseenter
differs in that it doesn't bubble and that it isn't sent when the pointer is moved from one of its descendants' physical space to its own physical space.
If you use mouseover
, it will bubble up, so the event listener will be triggered on pointed element and its ancestors (your 1st problem).
If you use mouseenter
, it won't be triggered when the pointer is moved from one of its descendants' physical space to its own physical space (your 2nd problem).
What you need is mouseover
without bubbling. There's no specific event for that, but you can manually prevent it from bubbling using stopPropagation
:
$("body").on("mouseover", "*", function (e) {
e.stopPropagation();
var html = $(this).attr("title");
console.log(html);
$("#result").text(html);
});
Upvotes: 1
Reputation: 1682
This problem can be easily fixed by adding "[title]"
to the selector.
You can find the working demo here in jsfiddle
Upvotes: 0
Reputation: 1028
this is due to event bubbling, you can refer for solution
http://api.jquery.com/event.stoppropagation/
Also you can use global flag variables to detect events
Upvotes: 2