1

I have a animated gif as a background image which is activated when you hover a link. But once activated it just keeps on playing even though you're not hovering the link and even though it isn't visible. Are there any ways to restart the gif every time you hover over the link, using css only?

Here is my code so far

<div id="zichtbaar">
<a href="?link?">Zichtbaar<span></span></a>

and the CSS

#zichtbaar a span { 
display: none; 
background-image: url("background.gif");
background-size: contain;
background-position: fixed;
background-repeat: no-repeat;
position: fixed;
width: 100%;
height: 100%;
left: 25%;
top: 35px;
z-index:-9999;                                              
#zichtbaar a:hover span { 
display:block;  
}
Jeppe Pendrup
  • 103
  • 1
  • 2
  • 7

3 Answers3

2

I'd create a second image, a still in .png format, and would change the source of the image on :hover so that when the user hovers the image, the source is the animated gif, and when he mouses out, the source is replaced with the still image and that would visually reset the image. Something like this:

#zichtbaar a span { 
background-image: url("StillImageOfTheGif.png");
}

#zichtbaar a span :hover { 
background-image: url("background.gif");
}

In addition, I'd add an <img> element of the still .png image with a hidden attribute so that the image loads when the page loads and thus avoid a delay when the user triggers the hover.

Edit based on comments and javascript version.

<a id="zichtbaar">Zichtbaar</a>
<img id="DasBild" src="https://jepen84.github.io/github.io/images/static_ice.gif" />

function Start() {

    $('#zichtbaar').on({

    mouseenter: function () { $('#DasBild').prop('src', 'https://jepen84.github.io/github.io/images/ice_t.gif') },
    mouseleave: function () { $('#DasBild').prop('src', 'https://jepen84.github.io/github.io/images/static_ice.gif') }

  });
}

$(Start);
frenchie
  • 51,731
  • 109
  • 304
  • 510
1

You need to use hover

#zichtbaar a span :hover {
    background-image: url("background.gif");
Ravi
  • 30,829
  • 42
  • 119
  • 173
1
    <img src="URL_OF_FIRST_IMAGE_SOURCE" 
    onmouseover="this.src='URL_OF_SECOND_IMAGE_SOURCE'" 
    onmouseout="this.src='URL_OF_FIRST_IMAGE_SOURCE_AGAIN'" />

I also had the same issues and this solution solved my problem perfectly it also help me tidy my CSS stylesheet cause it also replaces the use of stating a hover effect

Check it out here on fiddle: a link!

  • The question asker was using `CSS` to display their image; with `background-image`. So this wouldn't work in that case. – treckstar Aug 04 '22 at 00:44
  • I understand his question sir Am just giving him another alternative to achieve his task I also had same issues and this method help me gain more control over the task – Bright Lazarus Aug 05 '22 at 07:11