javascript-and-jquery tutorials
Comprehensive
Javascript and jQuery Tutorials
Front-end developers can enhance their expertise in website element creation through these JavaScript and jQuery tutorials. By exploring the latest client-side libraries, you'll acquire the advanced skills necessary to differentiate yourself as a more proficient coder.
Javascript and jQuery Tutorials:
How to Create Image Zoom on Hover and Cursor Move Using jQuery for Dynamic Web Previews?
reading time
Reading Time:
00:07 Minutes
implement time
Implement Time:
00:20 Minutes
Live Preview Links
Screenshot
image zoom on hover and cursor move using jquery 2506082215022506

Introduction to Image Zoom Techniques

Image zoom effects are widely used in modern web development to enhance user experience. They provide a detailed view of images without requiring users to open a separate page or download the image. This is essential for e-commerce websites, photography portfolios, and product previews.

Benefits of Image Zoom:
  • Improves user engagement by providing interactive previews.
  • Enhances accessibility for users who want a closer look at details.
  • Saves page space, avoiding large images while keeping quality high.
  • Increases conversions for e-commerce by giving users confidence in product details.

In this tutorial, we will implement an image zoom effect on hover and cursor movement using jQuery. The technique will be responsive and cross-browser compatible, ensuring a seamless experience across different devices and browsers.

HTML Code for Image Zoom Effect

First, we need a simple HTML structure for the image zoom effect. The zoom effect will work inside a wrapper container that holds both the normal and zoomed versions of the image.

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>
Explanation:
  • The .image-container holds both the main image and the zoom-view.
  • The .zoom-view is an empty div that will show the zoomed portion of the image.
  • jQuery will handle mouse movement to create the zoom effect dynamically.

CSS Code for Styling and Responsiveness

The following CSS ensures the image zoom effect works smoothly across different screen sizes.

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;
}
Explanation:
  • .image-container ensures the image stays contained and responsive.
  • .zoom-view acts as the magnified preview.
  • display: none; keeps .zoom-view hidden until hover occurs.

jQuery Code for Image Zoom on Hover and Cursor Move

The following jQuery script handles the zoom effect dynamically:

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();
	});
});
Explanation:
  • Tracks mouse movement inside the image container.
  • Calculates the background position dynamically based on cursor position.
  • Adjusts background size to maintain zoom ratio.
  • Hides zoom view when the cursor leaves the image.

How It Works

  1. User hovers over the image: The mousemove event is triggered.
  2. Cursor position is tracked: The script calculates the x and y coordinates.
  3. Zoom view updates dynamically: The backgroundPosition of .zoom-view changes based on cursor movement.
  4. Zoom effect mimics a magnifying glass: The zoomed area follows the cursor.
  5. Leaving the image hides zoom preview: The mouseleave event ensures a clean exit.

Customization & Tweaks

You can tweak the effect to suit different needs:

  • Change zoom factor: Modify let zoomSize = 3; to increase or decrease zoom.
  • Modify zoom area size: Adjust .zoom-view { width: 150px; height: 150px; }.
  • Change border color: Customize .zoom-view { border: 2px solid #ccc; }.
  • Support mobile devices: Implement touch gestures instead of mousemove.
  • Enable smooth transitions: Use transition: all 0.2s ease-in-out; in CSS.
Conclusion

Implementing an image zoom effect using jQuery is a great way to enhance user experience and engagement. This tutorial provided a complete step-by-step guide with responsive HTML, CSS, and jQuery scripts.

By understanding the concepts covered here, you can customize the effect for various use cases like product previews, portfolios, and galleries.

Start implementing this on your website today and provide users with a better interactive image viewing experience!

More Tutorials

User interaction pseudo-classes in CSS allow developers to apply styles dynamically based on how users interact with elements. They enable changes when a user hovers, clicks,

Creating a stunning dispersion effect can elevate your profile picture and make it stand out on social media. This guide will walk you through the process step by step,

PHP is one of the most widely used languages for web development, and MySQL is a powerful open-source relational database management system (RDBMS). Establishing a secure and

Vertical centering is a crucial aspect of web design, ensuring content appears balanced and aesthetically pleasing across different screen sizes. Whether it's a login form, a

In modern web design, customizing bullet points for unordered and ordered lists can significantly enhance the visual appeal and user experience of a website. While default

Creating visually appealing and professional designs in Adobe Illustrator often hinges on precise alignment. While freehand drawing has its place, achieving pixel-perfect

HTML5 introduced a set of semantic elements that provide meaning to the structure of web pages. Unlike non-semantic elements like and , which tell us nothing about their

Double exposure portraits are a captivating artistic effect combining two images into one surreal composition. Using Adobe Photoshop’s layer blending modes and masking

Development Tools
css beautifier tool

Our online CSS beautifier & minifier is the professional choice for clean code. It offers customizable options for formatting, beautification, and minification. Enhance your CSS for optimal results now!

html beautifier tool

Our online HTML beautifier is the professional choice for cleaning up code. Compress & format HTML for improved structure and readability, with just a few clicks. Start beautifying today!

css gradient generator tool

Design unique CSS gradients with our easy to use, professional generator. Choose colors and customize with advanced features. Lightweight for fast and optimized output!

sort words tool

Use our powerful sort words tool to arrange text by alphabetical order or character length. Many options available to format the output as desired. Clean up your lists now, quickly and easily!

encoder decoder tool

Professional-grade text encoding and decoding is here with our advanced tool. Sophisticated features and capabilities for all your complex data transformation needs. Start now!

css filter generator tool

Our lightweight CSS filter generator lets you create CSS filters using hex values with multiple advanced options. Get the perfect look for your elements with this powerful & efficient tool!

email extractor tool

Extract email IDs from messy text with a single click using our professional tool. Lightweight & efficient, streamlines the process for you, saving time. Try now for effortless email extraction!

lorem ipsum generator tool

Our online Lorem Ipsum generator provides the best solution for your demo content needs. It offers many options, allowing you to create perfect placeholder text with precision. Get started now!

Our Services
website development service

Our Website Development Service offers custom, responsive design, ensuring seamless user experience across devices. From concept to launch, we create dynamic, SEO-friendly sites to elevate your online presence and drive engagement.

website redesign service

Revamp your online presence with our Website Redesign Service! We specialize in creating modern, user-friendly designs that boost engagement and conversion rates. Transform your site today for a sleek, professional look that stands out.

psd to html5 service

Transform your PSD designs into pixel-perfect, responsive HTML5 code with our professional PSD to HTML5 conversion service. Enjoy clean, SEO-friendly, and cross-browser compatible code tailored to bring your vision to life seamlessly.

logo design service

Elevate your brand with our professional Logo Design Service. We create unique, memorable logos that capture your business's essence. Stand out in the market with a custom logo designed to leave a lasting impression.

seo search engine optimization service

Boost your site's search engine presence! We offer expert SEO solutions, including image and code enhancements, to achieve top positions on Google, Bing, and Yahoo. Let us drive qualified traffic to your business today!

social media marketing service

Boost your brand with our Social Media Marketing Service! We specialize in crafting engaging content, driving growth through targeted ads, and maximizing your online presence. Drive growth and connect with your audience effectively.

wordpress development service

Experience our WordPress development services, offering tailored solutions for custom themes, plugins, and seamless integrations. Enhance your online presence with our responsive, secure, and success-optimized WordPress solutions.

image enhancement service

Enhance your website's visual appeal: We sharpen icons/images, correct RAW files & repair damaged/distorted/overly bright photos. Expect natural-colored, high-resolution JPEGs, complete with photographic effects & upscaling.

Blog Post

In the dynamic world of web development, the visual appeal and user experience of a website are paramount. At the heart of this lies CSS (Cascading Style Sheets), the language that dictates how...

In today's digital landscape, a stunning and functional website is no longer a luxury but a necessity. Whether you're an aspiring web designer, a budding entrepreneur, or a seasoned professional looking to sharpen...

AI is fundamentally reshaping website development, automating tedious tasks, enabling hyper-personalization, and accelerating development cycles, which presents both immense opportunities for those who adapt and significant risks for developers who ignore this technological...

Choosing the right server infrastructure is one of the most critical decisions any business or individual with an online presence will make. Get it right, and you have a stable, performant foundation for...

In the fast-paced world of web development, efficiency and productivity are paramount. For PHP developers, the choice of a code editor can significantly impact their workflow, making the difference between a cumbersome coding...

Choosing between a career as a designer or a developer can feel like standing at a crossroads. Both roles are integral to creating digital products, yet they demand vastly different skill sets, mindsets,...

In the fast-paced digital world, your brand’s visual identity plays a pivotal role in grabbing attention, building trust, and driving engagement. Whether it's a social media post, website design, or ad creative, graphic...

In today’s digital world, having a strong online presence is critical for businesses and individuals alike. When it comes to building a website, one of the most important decisions you’ll face is choosing...