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:06 Minutes
implement time
Implement Time:
00:20 Minutes

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://www.roxunlimited.com/template/image/Rental-Properties-Mockup.webp" 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: 400px;
	overflow: hidden;
}

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

.zoom-view {
	position: absolute;
	width: 150px;
	height: 150px;
	background: url('https://www.roxunlimited.com/template/image/Rental-Properties-Mockup.webp') 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

PHP Output Buffering is an essential feature in PHP Web Development that helps developers manage and manipulate output before sending it to the browser. It allows capturing

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

Date and time handling is a crucial aspect of PHP development. Whether you're displaying timestamps, logging events, or managing time-sensitive operations, understanding

Layer styles are the secret weapon of many professional designers, offering a quick and effective way to add depth, texture, and dimension to your artwork. Whether you’re

In the ever-evolving world of web development, creating responsive designs that seamlessly adapt to various screen sizes is crucial for delivering an optimal user experience.

A responsive navigation menu is essential for ensuring smooth and user-friendly navigation across devices. The way dropdown menus behave on desktop and mobile can

In modern HTML and CSS development, keeping two divs side by side is a fundamental layout requirement. Whether you're building a responsive website or a fixed-width layout,

In today’s fast-paced world of WordPress web development, ensuring your website is free from coding errors is essential for a smooth user experience and optimal

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

Introduction In today's digital age, having a well-optimized website is crucial for businesses and individuals alike. A website that loads quickly, is easy to navigate, and provides a seamless user experience can greatly...

Introduction Graphic design is a dynamic and creative field that requires the right tools to bring your visions to life. While there are many high-end paid software options available, not everyone can afford...

HTML5 Semantic Elements have become an important factor in improving SEO rankings due to their ability to provide search engines with more meaningful information about the content of a webpage. These elements go...

JavaScript extended libraries offer a wide range of capabilities for creating interactive and dynamic elements on websites. With these libraries, you can easily incorporate features such as drop-down menus, popups, modals, banner sliders,...

Colors are an incredibly important factor in website design, because they can have a significant effect on user experience and engagement. Colors create visual stimulation, which can influence how users process information. Using...

If you want your website and graphic designs to capture attention, incorporating exceptional fonts is a must! Incorporating elegant typefaces has the capacity to bring your design up a notch, making it more...

In the ever-evolving landscape of digital marketing, Search Engine Optimization (SEO) remains an important strategy for increasing organic traffic and increasing a website's online visibility. However, as search engines continually refine their algorithms...

Adobe Photoshop is a prominent software in image editing and retouching, offers a variety of functionalities. However, it might not be the ideal choice for all users due to several drawbacks. Its interface,...