I need a hoverable transparent animation for a website, so that it glows when the mouse is over it. I could use two gifs or svgs one on top of another, but (as far as I know) there's no control of the current frame so I tried spritesheets with JavaScript and an if/else inside of every image in order to show the hovered, glowing version or the non-glowing depending on the users's mouse position.
However, there is yet another thing I tried: instead of a single spritesheet, why not cut it and put it all in the same position within a container div? They all start in display:none and they appear at the rate JavaScript tells them to. It works quite nicely. Here is my HTML:
<div id="animation">
<img src="frame1.png">
<img src="frame1glow.png">
<img src="frame2.png">
<img src="frame2glow.png">
</div>
There are many more frames, of course. This is the JavaScript controller (for two frames):
var animation_hovered = false;
animation.onmouseover = function(){animation_hovered = true;}
animation.onmouseout = function(){animation_hovered = false;}
window.setInterval(function(){
if(animation_hovered == false){
document.querySelector('#animation img:nth-child(1)').style.display = "initial";
document.querySelector('#animation img:nth-child(4)').style.display = "none";
document.querySelector('#animation img:nth-child(3)').style.display = "none";
}
else{
document.querySelector('#animation img:nth-child(2)').style.display = "initial";
document.querySelector('#animation img:nth-child(4)').style.display = "none";
document.querySelector('#animation img:nth-child(3)').style.display = "none";
}
window.setTimeout(function(){
if(animation_hovered == false){
document.querySelector('#animation img:nth-child(3)').style.display = "initial";
document.querySelector('#animation img:nth-child(1)').style.display = "none";
document.querySelector('#animation img:nth-child(2)').style.display = "none";
}
else{
document.querySelector('#animation img:nth-child(4)').style.display = "initial";
document.querySelector('#animation img:nth-child(1)').style.display = "none";
document.querySelector('#animation img:nth-child(2)').style.display = "none";
}
}, 300);
}, 600);
It seems bulky, but this approach gives you absolute control over your frames and it works nicely. Also, by not using a spritesheet, you can keep your layout pretty simple (or at least a big spritesheet seems to me a bit difficult to hide in my web interface; cut it seems simpler).
Does anyone think I am doing something wrong or could be enhanced in any way?