skip to Main Content

I have an image and a list next to it. I want the image to change to a different source whenever I hover over each item in the list depending on which one it is. For example if I hover over the <div> "Czech", the image source will change to a map with Czech-speaking areas highlited, but if I hover over the <div> "Resian" then the image source in the neighboring (website-space-speaking-wise) div will change to a map with areas speaking the Resian dialect of Slovenian highlited.

I’ve tried JavaScript functions and CSS.

3

Answers


  1. <img src="" id="image" />
    <ul>
    <li onmouseenter="changeSource('maldives')" >Maldives</li>
    <li onmouseenter="changeSource('lakshadweep')" >Lakshadweep</li>
    </ul>
    
    const sources = {
    maldives: "https://maldives.image.com",
    lakshdweep: "https://lakshadweep.image.com"
    }
    
    
    function changeSource(imgSrc){
      document.querySelector('#image').src = sources[imgSrc];
    }
    
    Login or Signup to reply.
  2. Html:

    <div class="container">
     <div class="language" onmouseover="changeImage('czech')">Czec</div>
     <div class="language" onmouseover="changeImage('resian')">Resian</div>
     <img id="mapImage" src="default.jpg" alt="Map Image">
    </div>
    

    JavaScript:

    function changeImage(language) {
     var img = document.getElementById('mapImage');
     if (language === 'czech') {
       img.src = 'czech-map.jpg';
     } else if (language === 'resian') {
       img.src = 'resian-map.jpg';
     }
    }
    

    Css:

    .language {
      cursor: pointer;
     }
    
    Login or Signup to reply.
  3. You can do this easily by using JavaScript. You need to replace newImage.jpg and default.jpg with your src url.

    CSS:

    #imageContainer {
      width: 300px;
      height: 200px;
      overflow: hidden;
    }
    
    #hoverDiv {
      padding: 10px;
      background-color: lightgray;
      cursor: pointer;
    }
    

    HTML:

    <div id="imageContainer">
      <img id="image" src="default.jpg" alt="Default Image">
    </div>
    <div id="hoverDiv">Hover me</div>
    

    Javascript:

    var image = document.getElementById('image');
    var hoverDiv = document.getElementById('hoverDiv');
    
    // Set the new image source when hovering over the hover div
    hoverDiv.addEventListener('mouseover', function () {
      image.src = 'newImage.jpg'; // Change this to the path of your new image
    });
    
    // Reset the image source when the mouse leaves the hover div
    hoverDiv.addEventListener('mouseout', function () {
      image.src = 'default.jpg'; // Change this to the path of your default image
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search