Search code examples
javascriptmouseoveronmouseovermouseoutonmouseout

Insert text over an image and change the text by hovering the mouse over (JavaScript)


I have this HTML code and I want to insert a descriptive text for this image, in the center of it. After that I would like to change the text by hovering over the image. Any thoughts on that? I tried several solutions, but most failed to do that for several images, and not for just one in particular.

<div class="col-4 col-6-medium col-12-small">
    <a href="#" class="image fit">
        <img src="images/pic01.jpg" alt="">
    </a>
</div>

Solution

  • for such an assignment you don't need javascript

    let it browser do for you with #pureCss

    (using javascript for manipulating with DOM or changing classes on divs are unnecessary overkill)

    you can add whatever animation with higher performance (using css)

    .image.fit{
      /* block capabilities, but still next to each other */  
      display: inline-block;
      /* be the parent for position absolute later */
      position: relative;
    }
    
    .image.fit .normal, .image.fit .hover {
      /* position of the box */
      position: absolute;
      bottom: 5%;
      left: 5%;
      right: 5%;
    
      /* nice box with padding even for multiline */
      background-color: rgba(255,255,255,0.6);
      padding: 5%;
      text-align: center;
      font-family: Arial;
      color: #333;
    
      /* animate fade, rather than blinking */
      transition: opacity 0.5s;
    }
    
    .image.fit .normal {
      opacity: 1; /* visible by default */
    }
    .image.fit:hover .normal {
      opacity: 0; /* not visible on hover */
    }
    
    .image.fit .hover {
      opacity: 0; /* not visible by default */
    
      /* optional position on top (remove, for the same place) */
      top: 5%;   
      bottom: auto;
    }
    .image.fit:hover .hover {
      opacity: 1; /* visible on hover */
    }
    <div class="col-4 col-6-medium col-12-small">
        <a href="#" class="image fit">
            <img src="https://picsum.photos/id/1015/300/150" alt="">
            <div class="normal">water</div>
            <div class="hover">you can go tomorrow, tickets available</div>
        </a>
        <a href="#" class="image fit">
            <img src="https://picsum.photos/id/1016/300/150" alt="">
            <div class="normal">rocks</div>
            <div class="hover">Lorem Ipsum: Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit...</div>
        </a>
    
    </div>