8

#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.

cozycone
  • 175
  • 6

1 Answers1

-1

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>