Image Zoom on Hover and Cursor Move

by jay prakash

HTML

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Image Zoom on Hover using jQuery</title>
	<link rel="stylesheet" href="styles.css">
</head>
<body>
	<div class="image-container">
		<img src="https://images.unsplash.com/photo-1501785888041-af3ef285b470?auto=format&fit=crop&w=1600&q=80" class="main-image" alt="Zoomable Image">
		<div class="zoom-view"></div>
	</div>
	
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script src="script.js"></script>
</body>
</html>

CSS

body {
	font-family: Arial, sans-serif;
	display: flex;
	justify-content: center;
	align-items: center;
	height: 100vh;
	background-color: #f5f5f5;
}

.image-container {
	position: relative;
	width: 600px;
	overflow: hidden;
}

.main-image {
	width: 100%;
	display: block;
	cursor: crosshair;
}

.zoom-view {
	position: absolute;
	width: 150px;
	height: 150px;
	background: url('https://images.unsplash.com/photo-1501785888041-af3ef285b470?auto=format&fit=crop&w=1600&q=80') no-repeat;
	border: 2px solid #ccc;
	display: none;
	pointer-events: none;
}

JavaScript

$(document).ready(function() {
	$('.image-container').mousemove(function(e) {
		let zoomView = $('.zoom-view');
		let image = $('.main-image');
		let imageOffset = image.offset();
		let posX = e.pageX - imageOffset.left;
		let posY = e.pageY - imageOffset.top;
		
		if (posX < 0 || posY < 0 || posX > image.width() || posY > image.height()) {
			zoomView.hide();
			return;
		}
		
		zoomView.show();
		
		let zoomSize = 3;  // Zoom scale factor
		let bgPosX = -((posX * zoomSize) - (zoomView.width() / 2));
		let bgPosY = -((posY * zoomSize) - (zoomView.height() / 2));
		
		zoomView.css({
			top: posY - zoomView.height() / 2,
			left: posX - zoomView.width() / 2,
			backgroundPosition: `${bgPosX}px ${bgPosY}px`,
			backgroundSize: `${image.width() * zoomSize}px ${image.height() * zoomSize}px`
		});
	}).mouseleave(function() {
		$('.zoom-view').hide();
	});
});