JavaScript Image Zoom on Hover

JavaScript Image Zoom
Project: Pure javascript image zoom
Author: Foolish Developer
Edit Online: View on CodePen
License: MIT

This JavaScript code snippet helps you to create an image zoom effect on hover. It defines a function called zoom() that takes an event object as its parameter. Inside the function, it first assigns the element that triggered the event to a variable called zoomer.

Then it checks whether the event was triggered by a mouse or a touch event, and sets the offsetX and offsetY variables accordingly. It then calculates the x and y position of the cursor within the zoomer element by dividing the offsetX and offsetY values by the width and height of the zoomer element respectively, and multiplying the result by 100 to get a percentage.

Finally, it sets the background position of the zoomer element to the x and y values, creating a zoom effect.

How to Create JavaScript Image Zoom

Create the HTML structure for an image zoom effect as follows:

<!DOCTYPE html>
<!-- Design by foolishdeveloper.com -->
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Pure javascript image zoom </title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <style media="screen">
    figure.zoom {
  background-position: 50% 50%;
  position: relative;
  margin: 150px auto;
  border: 5px solid white;
  box-shadow: -1px 5px 15px black;
  height: 300px;
  width: 500px;
  overflow: hidden;
  cursor: zoom-in;
}
figure.zoom img:hover {
  opacity: 0;
}
figure.zoom img {
  transition: opacity 0.5s;
  display: block;
  width: 100%;
}
  </style>
  <title>Document</title>
</head>
<body>
  <figure class="zoom" onmousemove="zoom(event)" style="background-image: url(https://i.pinimg.com/originals/2b/de/de/2bdede0647e3cdf75b44ea33723201d9.jpg)">
  <img src="https://i.pinimg.com/originals/2b/de/de/2bdede0647e3cdf75b44ea33723201d9.jpg" />
</figure>
<script type="text/javascript">
function zoom(e){
  var zoomer = e.currentTarget;
  e.offsetX ? offsetX = e.offsetX : offsetX = e.touches[0].pageX
  e.offsetY ? offsetY = e.offsetY : offsetX = e.touches[0].pageX
  x = offsetX/zoomer.offsetWidth*100
  y = offsetY/zoomer.offsetHeight*100
  zoomer.style.backgroundPosition = x + '% ' + y + '%';
}
</script>
</body>
</html>

That’s all! hopefully, you have successfully created our project.

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *