JavaScript - Image zoom on hover

JavaScript - Image zoom on hover

Hello colleagues.

In today's article, we'll look at how you can create a simple image scaling script with jQuery that will provide a nice magnifying glass effect when hovering over an image.

 

HTML code.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Zoom Image On Hover</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
    <h1>Zoom Image On Hover</h1>
    <div class="magnify">
        <div class="magnifier" style="background-image: url(images/6498354090.png);"></div>
        <div class="magnified">
            <img src="images/6498354090.png" />
        </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.slim.min.js"></script>
<script src="script.js"></script>
</body>
</html>

 

CSS code.

.container{
    display: table;
    margin: 0 auto;
}
.container h1{
    text-align: center;
}

body {
    padding: 0px;
    background-color: #97b8ed;
}

.magnify {
    margin: 20px auto;
    display: inline-block;
    position: relative;
}
.magnify .magnified {
    display: block;
    z-index: 10;
    margin: auto;
    width: 600px;
    height: 450px;
    border: 5px solid #fff;
}
.magnify .magnifier {
    height: 200px;
    width: 200px;
    position: absolute;
    z-index: 20;
    border: 4px solid white;
    border-radius: 50%;
    background-size: 1000%;
    background-repeat: no-repeat;
    margin-left: -100px !important;
    margin-top: -100px !important;
    pointer-events: none;
    display: none;
}
img{
    width: 100%;
    height:100%;
}

 

JavaScript code.

$(".magnified").hover(function(e){
  var imgPosition = $(".magnify").position(),
      imgHeight = $(".magnified").height(),
      imgWidth = $(".magnified").width();
  $(".magnifier").show();
  $(this).mousemove(function(e){
    
    var posX = e.pageX - imgPosition.left,
        posY = e.pageY - imgPosition.top,
        percX = (posX / imgWidth) * 100,
        percY = (posY / imgHeight) * 100,
        perc = percX + "% " + percY + "%";
    $(".magnifier").css({
      top:posY,
      left:posX,
      backgroundPosition: perc
    });
  });
}, function(){
  $(".magnifier").hide();
});

 

Thank you all, I hope my article was of some help to you.

 

SIMILAR ARTICLES

jQuery carousel with magnifying glass effect
jQuery carousel with magnifying glass effect
WEB
jQuery plugin to enlarge image with magnifying glass
jQuery plugin to enlarge image with magnifying glass
WEB
jQuery - Image gallery with zoom on hover
jQuery - Image gallery with zoom on hover
WEB