0

As soon as I load or reload the page. The gif i've included in the html starts playing.

$('.text').mouseover(function() {
$('.hover').css("visibility", "visible"); })

$('.text').mouseout(function() {
$('.hover').css("visibility", "hidden"); });

I want the gif to start whenever I hover over the relevant element and stop when I take my cursor off. This JS is in a script tag within the body of HTML doc. It works after I hover over the 'text' element for the first time. Would love some guidance on what I am doing wrong.

skl_dev
  • 1
  • 2
  • 1
    What is the visibility of the element when the page loads (i.e. before you hover for the first time)? Perhaps it's set to `visibility: visible` on load? – Cully Oct 10 '19 at 23:29
  • Please include more of your HTML, specifically the markup for `.text` and `.hover`. Do you have more elements with those classes on the page? – AP. Oct 10 '19 at 23:38
  • Possible duplicate of [Stopping GIF Animation Programmatically](https://stackoverflow.com/questions/3688460/stopping-gif-animation-programmatically) – joyBlanks Oct 10 '19 at 23:46
  • you could convert your gif to a sprite and manually animate with css and pause/play with js. or use a library Supergif or do it manually using a canvas. – joyBlanks Oct 10 '19 at 23:48
  • @Cully that sounds like what the issue could be. I'm unsure on how to set the visibility state on the img element upon loading. – skl_dev Oct 11 '19 at 00:19
  • I'll post the suggestion as an answer. – Cully Oct 11 '19 at 04:34
  • @Salief Did that work? – Cully Dec 11 '19 at 06:39

1 Answers1

0

It's likely that the visibility of the image is visible on the initial page load. When you do your first mouseover, then mouseout, it gets set to hidden, which is your expected behavior. Try setting the visibility of the img to hidden, by one of these methods:

  1. Add a style in the head of the page:
<html>
  <head>
    <style>
      img.hover { visibility: hidden; }
    </style>
  </head>
  <body>
   <img src='path/to/image.gif' class='hover' />
  </body>
</html>
  1. Or, set the style inline in the image itself:
<html>
  <body>
   <img src='path/to/image.gif' class='hover' style='visibility: hidden' />
  </body>
</html>
Cully
  • 6,427
  • 4
  • 36
  • 58