I don't know JavaScript and it's safe to say this is my first code ever written in JS. I just needed to animate my GIFs when user hovers over them only. Googling separate concepts such as "string functions", "catch element mouse hover", "set element attribute", "get element attribute", "get elements by class", "var vs let" and so on, I came up with this:
var contentClass = document.getElementsByClassName("gifclass");
for(var i = 0; i < contentClass.length; i++)
{
let iElement = contentClass.item(i);
iElement.addEventListener("mouseenter", function(event)
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'gif');
}, false);
iElement.addEventListener("mouseleave", function(event)
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'png');
}, false);
}
}
Prerequisites:
- You need to have a static version of the GIF that ends in png (I did that with MS Paint).
- It works so long as the GIFs are within the same class
Example:
{
var contentClass = document.getElementsByClassName("gifclass");
for(var i = 0; i < contentClass.length; i++)
{
let iElement = contentClass.item(i);
iElement.addEventListener("mouseenter", function( event )
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'gif');
}, false);
iElement.addEventListener("mouseleave", function( event )
{
const srcAtt = iElement.getAttribute('src');
let result = srcAtt.slice(0, srcAtt.length - 3);
iElement.setAttribute("src", result + 'png');
}, false);
}
}
Hover me:
<img class="gifclass" src="https://gameeditor2.sirv.com/website/GIFs/game-mode.png" alt="" data-image-width="320" data-image-height="240">
All in all, my initial research on how to do that only pointed out examples where I had to do plenty of code for all of my 20+ GIFs and handle them separately.
It works, but considering that I don't know JS I was thinking it might be useful to share it for a review