Freddie Freddie - 7 months ago 32
Javascript Question

Force gif to reload after mouse leave

On my website I have several images that loop through a GIF animation on mouse hover, and return to a static image when the mouse leaves the picture.

I'd like the gif to play from its first frame when the mouse hovers. However, if I hover over a picture, move the mouse away, and hover again, the image will turn to the gif continuing from the last frame it was on.

Here is my HTML code:

<img id="menugif">


My CSS:

#menugif
{
padding-top: 15px;
height: 115px;
width: 125px;
content:url(../images/Hulk.png);
float: left;
}
#menugif:Hover
{
cursor:pointer;
content:url('../images/Hulk.gif');
float: left;
}


I'd be grateful to any solution, including Javascripts! Thank you all :)

Answer

This is a cheap way to fix it, but to resolve I did this:

Each HTML gif has its own ID:

<a id="single_image1" href="#"><img id="menugifHulk" src="images\hulk.png"></a>

Each one of these has it's own style, like so:

#menugifHulk
        {
            padding-top: 15px;
            height: 115px;
            width: 125px;
            float: left;
        }

And then each element has its own JavaScript:

var img = document.getElementById('menugifHulk');
img.addEventListener('mouseleave', function () {
    var imageUrl = img.src;
    img.src = "";
    img.setAttribute('src', 'images/Hulk.png');
}, false);
img.addEventListener('mouseover', function () {
    img.setAttribute('src', 'images/Hulk.gif');
}, false);

The java was in a function like this:

function GifReset()
{
    var img = document.getElementById('menugifHulk');
    img.addEventListener('mouseleave', function () {
        var imageUrl = img.src;
        img.src = "";
        img.setAttribute('src', 'images/Hulk.png');
    }, false);
    img.addEventListener('mouseover', function () {
        img.setAttribute('src', 'images/Hulk.gif');
    }, false);
}