Mouse over the image with magnifying glass in html

I added a magnifying glass for images in my webpage using the following instruction:

The magnified box stays on the image even if the mouse is not over it. How can I revise this in a way that the magnifying glass appears only when the mouse is over it?


3 answers

  • answered 2018-02-13 00:25 Gorgamite

    In HTML, there is an event called onmouseleave. You could make the element call a javascript function when your mouse leaves the image. Here's the link for more information: Here's the basics of it: onmouseleave="functionName()"

  • answered 2018-02-13 02:40 MMallette

    You can do this all in CSS using hover, no need for javascript copy the style sheet from below.

    * {box-sizing: border-box;}
    .img-magnifier-container {
    .img-magnifier-container:hover .img-magnifier-glass {
      position: absolute;
      border: 3px solid #000;
      border-radius: 50%;
      cursor: none;
      /*Set the size of the magnifier glass:*/
      width: 100px;
      height: 100px;
    .img-magnifier-glass {

  • answered 2018-02-13 09:10 DeclanMcD

    You need to add a onmouseout event to the magnifying glass div and an id to identify it, like this:

      glass = document.createElement("DIV");"glassId";
      glass.setAttribute("onmouseout", "hide()");

    Then add a show and hide function like this:

    function hide(){
        glass = document.getElementById("glassId").style.display = "none";
    function show(){
        glass = document.getElementById("glassId").style.display = "block";

    Finally add the mouseover event to the image itself:


    This will then hide the glass when the mouse leaves the glass (not the image) and show it when the mouse goes back into the image.