jqueryrandomhoverjquery-hover

Add random image on hover using jquery


It is difficult to modify HTML and CSS except for adding class and ID to div. So why I'm trying to process it using JS Jquery.

I'd want to show the GIF randomly when I hover over the image in the div.

When the mouseout, the effect should disappear so that the original image can be seen again.

enter image description here

(In this example, the goal is to have gif appear randomly.)

Here's the code I've been working on.

const ImgLinks = [
"https://media.giphy.com/media/tJ1jipvvMs4r7xuZnI/giphy.gif",
"https://media.giphy.com/media/XFpIo4jKuUrjQHYHeq/giphy.gif",
"https://media.giphy.com/media/uxunn6z4qKrGsND3II/giphy.gif",
"https://media.giphy.com/media/XxRl7rbKSFvXEFoNzv/giphy.gif"
]; //sources are examples.
    
function getRandHoverGif() {
  const index = Math.floor(Math.random() * ImgLinks.length);
  return ImgLinks[index];
}

$("#hover-ani").hover(
  function() {

I don't know how to complete the hover function.


Solution

  • Set image src on hover and remove src on hover out. Apply some CSS on image to get desire output.

    Example:

    const ImgLinks = [
      "https://media.giphy.com/media/tJ1jipvvMs4r7xuZnI/giphy.gif",
      "https://media.giphy.com/media/XFpIo4jKuUrjQHYHeq/giphy.gif",
      "https://media.giphy.com/media/uxunn6z4qKrGsND3II/giphy.gif",
      "https://media.giphy.com/media/XxRl7rbKSFvXEFoNzv/giphy.gif"
    ]; //sources are examples.
    
    function getRandHoverGif() {
      const index = Math.floor(Math.random() * ImgLinks.length);
      return ImgLinks[index];
    }
    
    $("#hover-ani").hover(
      function() {
        $("#img2").attr("src", getRandHoverGif());
      },
      function() {
        $("#img2").attr("src", "");
      }
    );
    #img1 {
      background-color: transparent;
      background-image: url("https://i.sstatic.net/XZ4V5.jpg");
      background-repeat: no-repeat;
      width: 600px;
      height: 400px;
      position: absolute;
      z-index: 1;
    }
    
    #img2 {
      position: absolute;
      top: 25px;
      left: 25px;
      z-index: 2;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="hover-ani">
      <img id="img1"></img>
      <img id="img2"></img>
    </div>

    Note: You can edit (customize) your CSS as per your requirement (gif position).