Here’s a tutorial that will guide you through the process of implementing a zoom image on mouseover using JavaScript. This interactive effect enhances user experience by allowing visitors to examine image details closely, triggered simply by hovering their mouse.
Setting Up the Basic HTML Structure
First, we need to create the basic HTML structure that will contain the image and the zoom area.
<div>Roll over image to zoom in</div>
<div id="img-zoomer-box">
<img src="https://images.unsplash.com/photo-1624211904722-c10788db74de?q=80&w=2340&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" id="img-1" />
<div id="img-2"></div>
</div>
<script src="./script.js"></script>
Applying CSS Styles
Next, we’ll style our elements with CSS to control the layout and appearance of the zoom effect. This includes setting the image container, the original image, and the zoomed-in view.
body {
margin: 12% 30%;
height: 450px;
overflow: scroll;
font-family: Arial, sans-serif;
color: #333;
background: #f4f4f4;
}
#img-zoomer-box {
width: 500px;
height: auto;
position: relative;
margin-top: 10px;
}
#img-1 {
width: 100%;
height: auto;
}
#img-zoomer-box:hover, #img-zoomer-box:active {
cursor: zoom-in;
display: block;
}
#img-zoomer-box:hover #img-2, #img-zoomer-box:active #img-2 {
opacity: 1;
}
#img-2 {
width: 340px;
height: 340px;
background: url('https://images.unsplash.com/photo-1624211904722-c10788db74de?q=80&w=2340&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D') no-repeat #FFF;
box-shadow: 0 5px 10px -2px rgba(0,0,0,0.3);
pointer-events: none;
position: absolute;
opacity: 0;
border: 4px solid whitesmoke;
z-index: 99;
border-radius: 100%;
display: block;
transition: opacity .2s;
}
const zoomer = (e => {
const imageBox = document.querySelector("#img-zoomer-box");
const original = document.querySelector("#img-1");
const magnified = document.querySelector("#img-2");
function handleMouseMoves(e) {
const style = magnified.style;
const x = e.pageX - this.offsetLeft;
const y = e.pageY - this.offsetTop;
const imgWidth = original.offsetWidth;
const imgHeight = original.offsetHeight;
let xperc = (x / imgWidth) * 100;
let yperc = (y / imgHeight) * 100;
//lets user scroll past right edge of image
if (x >= 0.01 * imgWidth) {
xperc *= 1.15;
}
//lets user scroll past bottom edge of image
if (y >= 0.01 * imgHeight) {
yperc *= 1.15;
}
style.backgroundPositionX = `${xperc - 9}%`;
style.backgroundPositionY = `${yperc - 9}%`;
style.left = `${x - 180}px`;
style.top = `${y - 180}px`;
}
imageBox.addEventListener("mousemove", handleMouseMoves);
})();







