Reputation: 599
I want my element to appear when the mouse enters a div, then follow the mouse and disappear once I leave the div.
I've mashed together the following code.
HTML:
<div id='box' class="box">
<img id="image" src="download.jpeg"/>
</div>
CSS:
#image {
position:absolute;
display: none;
}
JS:
$(document).mousemove(function(e){
$("#image").css({
left:e.pageX,
top:e.pageY
});
});
$('.box').mouseenter(_=> {
$('#image').show();
});
$('.box').mouseleave(_=> {
$('#image').hide();
});
The intended functionality is inconsistent but seems to work if the mouse leaves the div quickly.
Upvotes: 0
Views: 853
Reputation: 481
The img
is inside of the box. When you hover and the image comes under your cursor, you're ALWAYS inside the box (since that's where the image is inside of the DOM structure).
So modifying your DOM as such:
<div id='box' class="box"></div>
<img id="image" src="https://i5.walmartimages.ca/images/Large/580/6_r/875806_R.jpg"/>
And then modify your CSS to include:
#image {
pointer-events: none;
}
Should accomplish what you're looking for. Here is a Fiddle with the modified code, too.
Upvotes: 4