skip to Main Content

I’m trying to enable zoom on an image that’s transitioned when a user hovers their mouse over the standard image that’s shown on the page. This is the HTML code I’ve written so far.

<img src="default_img1.jpg" onmouseover="this.src='hover_img1.jpg';" onmouseout="this.src='default_img1.jpg';" width="120">

This code works as expected. When I hover the mouse over "default_img1.jpg", it transitions to "hover_img1.jpg" with no issues. I’ve seen several postings on how to code zoom functionality using JS and/or CSS, but I’d only want zoom enabled when the imaged is transitioned to "hover_img1.jpg". Any ideas? Thank you!

I’ve tried several CSS/JS zoom functions, but they enable zoom on both default_img1.jpg and hover_img1.jpg.

2

Answers


  1. If you want the zoom effect only on the hover image, you can use a combination of CSS and JavaScript.

    Create a wrapper for the image so that it doesn’t overflow when zoomed in. Also, define the zoom effect for an .active class, which we will toggle using JavaScript.

    .img-wrapper {
      overflow: hidden;
      width: 120px;
      height: auto;
      display: inline-block;
    }
    
    img.zoom-effect {
      transition: transform 0.5s ease-in-out;
    }
    
    img.zoom-effect.active {
      transform: scale(1.5); /* Adjust this for zoom level */
    }
    <div class="img-wrapper">
      <img id="myImage" src="default_img1.jpg" onmouseover="hoverImage();" onmouseout="defaultImage();" width="120">
    </div>
    
    <script>
      const imgElement = document.getElementById("myImage");
    
      function hoverImage() {
        imgElement.src = 'hover_img1.jpg';
        imgElement.classList.add('zoom-effect', 'active');
      }
    
      function defaultImage() {
        imgElement.src = 'default_img1.jpg';
        imgElement.classList.remove('active');
      }
    </script>

    Adjust your HTML to include the wrapper and a couple of event listeners. We’ll modify the mouseover event to add the .active class only if the source is the hover image. The mouseout event will both change the image back to default and remove the .active class.

    Login or Signup to reply.
  2. I feel the approach is too bulky
    How about this

    Html

    <img src="default_img1.jpg" />
    

    Css

    img{
     display: block;
     width: 100px;
     transform: scale(1);
     transition: transform .5s ease;
    }
    
    img:hover{
     transform: scale(1.3);
     transition: transform .5s ease;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search