Preview of images when cursor hovers to different options in a menu

I have an html page with a menu with 4 buttons having different products

Whenever the cursor hovers on each button it must display images of different products

Any example code/link on how to do it will be very helpful

I'm trying to accomplish this in HTML, CSS and JQuery

I've tried using the css :hover pseudoselector on the buttons and changing the visibility but it didn't work.

Answers 1

  • You need to reference the ids of both the buttons and the images.

    Since we are working with unreleated elements, we can't use the css hover pseudoselector. We have to listen for the mouseover or mouseenter event to determine whenever the cursor is over a button. Similarly, when the cursor leaves that button, we call the mouseout or mouseleave events.

    Here is an example using JavaScript.

    var dinosaur1 = document.getElementById("dinosaur1");
    var dinosaur2 = document.getElementById("dinosaur2");
    var dino1 = document.getElementById("dino1");
    var dino2 = document.getElementById("dino2");
    
    
    dinosaur1.addEventListener("mouseover", function() {
        dino1.style.visibility = "visible";
    });
    
    dinosaur1.addEventListener("mouseout", function() {
        dino1.style.visibility = "hidden";
    });
    
    dinosaur2.addEventListener("mouseover", function() {
        dino2.style.visibility = "visible";
    });
    
    dinosaur2.addEventListener("mouseout", function() {
        dino2.style.visibility = "hidden";
    });
    img {
      visibility: hidden;
    }

    This is even simpler in jQuery because we get to nest events.

    $("#dinosaur1").on("mouseover", function() {
      $("#dino1").css({"visibility": "visible"});
    }).on("mouseout", function() {
      $("#dino1").css({"visibility": "hidden"});
    });
    
    $("#dinosaur2").on("mouseover", function() {
      $("#dino2").css({"visibility": "visible"});
    }).on("mouseout", function() {
      $("#dino2").css({"visibility": "hidden"});
    });
    img {
      visibility: hidden;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="dinosaur1">Dinosaur 1</button>
    <button id="dinosaur2">Dinosaur 2</button>
    
    <img height="150" width="150" id="dino1" src="http://vignette4.wikia.nocookie.net/dinosaurs/images/5/55/T-rex-dinosaur-clip-art-T-Rex-Dinosaur_1.png/revision/latest?cb=20151118162207" />
    
    <img height="150" width="150" id="dino2" src="http://i.telegraph.co.uk/multimedia/archive/03520/Kunbarrasaurus_3520731b.jpg" />


Related Articles