Reputation: 130
I'm using JQuery and I'm looking to get the element of the cursor is hovering over, however, I'm after something like this
for example:
<div id="outerBox">OuterBox
<div id="innerBox">InnerBox
</div>
</div>
However the only events I can find are
mouseover()
mouseenter()
Upvotes: 2
Views: 76
Reputation: 3377
you could use the .hover API, first function triggers when you hover-in and the second when you hover-out, heres a sample:
$( "#outerBox" ).hover(
function() {
console.log("hola")
}, function() {
console.log("adios")
}
);
$( "#innerBox" ).hover(
function() {
console.log("innerHola")
}, function() {
console.log("innerAdios")
}
);
#outerBox {
display: block;
background-color: blue;
}
#innerBox {
display: block;
width: 50%;
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="outerBox">OuterBox
<div id="innerBox">InnerBox
</div>
</div>
Upvotes: 0
Reputation: 557
Use event propagation. When the mouse is on innerBox use the mousemove event to stopPropagation and it will not bubble to outerBox.
Refer this link https://www.sitepoint.com/event-bubbling-javascript/
Upvotes: 1
Reputation: 10520
I think you miss a little note here. Events by default during the propagation got two phases: capturing and bubbling. You can read more about them here.
It is something like this:
So whenever you click an item within another item, by default it will bubble trough the parent element, then the parent event will get called. To avoid such a thing you should use .stopPropagation()
, so the actual code of yours should be something like this:
document.getElementById("outerBox").addEventListener("mouseover", function () {
console.log("Mouse is over outer box");
});
document
.getElementById("innerBox")
.addEventListener("mouseover", function (event) {
event.stopPropagation();
console.log("Mouse is over inner box");
});
<div id="outerBox">OuterBox
<div id="innerBox">InnerBox
</div>
</div>
Upvotes: 2
Reputation: 631
You can simply do this on jQuery.
/* Mouse Enter */
$('.outerBox').bind('mouseover',function(){
alert("true");
});
/* Mouse Outer */
$('.innerBox').bind('mouseout', function(){
alert("false");
});
Upvotes: 0