Triggering :hover on moving element without moving mouse
Asked Answered
M

1

9

#box {
  animation: scroll 2s linear infinite;
  width: 100px;
  height: 100px;
  background: red;
}

#box:hover {
  background: green;
}

@keyframes scroll {
  from {transform: none;}
  to {transform: translateX(400px);}
}
<div id="box"></div>

If you hover over the box, it stays green if you don't move the mouse after. If you put your mouse in its path and don't move, it doesn't trigger the hover.

Is there a way of triggering hover without moving the mouse in this case?

Edit: Without using JavaScript.

Marie answered 5/8, 2018 at 4:53 Comment(4)
#30427586 might be useful.Hydroquinone
#23831610 also seems to have the same issue.Hydroquinone
I'm not sure you can do this without jsGallous
No, it's impossible to do without JS. You would need JS to continually update the page.Evilminded
G
0

I know you don't want a javascript solution. However I'm not sure there is a solution without it. You can't trigger a mouse event when the mouse is doing nothing.

In the meantime I've added a solution with javascript, as it may help other people searching for answers with javascript solutions and landing on this question.

The last co-ordinates of the mouse as it moves are stored as variables x and y. The coordinates of the box can be found at any time using Element.getBoundingClientRect(). A function to see if the mouse pointer is sitting within the box can be set to run at any chosen interval. This would be something that would be tweaked depending on each circumstance.

The only issue is if the mouse is not moved at all when opening this page.

var x = 0;
var y = 0;
var box = document.querySelector("#box");
document.onmousemove = function(e){
    x = e.pageX;
    y = e.pageY;
}
setInterval(findMouse, 50);
function findMouse(){
    // Looking for the updated coordinates of the box
    var movingBox = box.getBoundingClientRect();

    if( x>=movingBox.left && x<=movingBox.right
            && y>=movingBox.top && y<=movingBox.bottom)
        document.getElementById("box").style.backgroundColor = "green";
    else
        document.getElementById("box").style.backgroundColor = "red";

}
#box {
	animation: scroll 2s linear infinite;
	width: 100px;
	height: 100px;
	background: red;
}

#box:hover {
	background: green;
}

@keyframes scroll {
	from {transform: none;}
	to {transform: translateX(400px);}
}
<div id="box"></div>
Gallous answered 5/8, 2018 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.