skip to Main Content

I have a flexbox with a div for an image and another div with text links. It looks something like this:

Flexbox

I’d like to make it so that when you hover over a text link, the initial image will change to a different image, then change back to the first image once you hover away from the text.

Like this

But I’m not sure how to write the JavaScript to do this. Most of the examples I found online only explain how to change the image when hovering over the image itself. I was wondering if anyone has an example of changing the image when hovering over a different element?

Thanks!

This is just a simplified version of the html and css for my flexbox, I’m not sure how to write or implement the script.

HTML:

<div class="topics">

    <div class="links">
        <a href="#"><p> Topic 1 </p></a>
        <a href="#"><p> Topic 2 </p></a>
        <a href="#"><p> Topic 3 </p></a>
    </div>
        
    <div class="image"> 
    <img src="#">
    </div>

</div>

CSS:

div.topics {
  display: flex;
  flex-direction: row;
  border: 5px solid black;
}

@media (max-width: 560px) {
 div.topics {
    flex-direction: column;
    }
  }

div.links {
  flex: 60%;
}

div.image {
  flex: 40%;
} 

2

Answers


  1. You can listen for mouseenter and mouseleave events for the target elements. On mouseenter, attach a new url src; on mouseleave set it back to the default src.

    HTML

    <div class="topics">
    
    <div class="links">
        <a href="#"><p> Topic 1 </p></a>
        <a href="#"><p> Topic 2 </p></a>
        <a href="#"><p> Topic 3 </p></a>
    </div>
        
    <div class="image"> 
    <img id = "my-img" src="">
    </div>
    

    CSS

    .topics {
        display: flex;
    }
    
    img {
       width: 100px;
       height: 100px;
    }
    

    JS

    const imageUrls = [
       "url1" , // default URL
       "url2",
       "url3"
    ];
    const links = document.getElementsByTagName("a");
    const imageEl = document.getElementById("my-img");
    imageEl.setAttribute('src', imageUrls[0]); // Set default image
    
    for(let i = 0; i < links.length; i++) {
      links[i].addEventListener("mouseenter", (e) => {
         imageEl.src = imageUrls[i];
      });
      links[i].addEventListener("mouseleave", (e) => {
         imageEl.setAttribute('src', imageUrls[0])
      });
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search