Mon - Sun 8.00 AM - 8.00 PM
[email protected]
Home
Articles
Our Courses
HTML 5
CSS
JavaScript
MySql
PHP
Laravel
Bootstrap
Our Tutorials
PHP
JavaScript
HTML
Laravel
MySQL
JQuery
CSS
Git
Bootstrap
Vue JS
Android
Ui Code Snippets
Chat Box
Range Slider
Radio Button
Select Box
Nav Bar
Other
Testimonial
Carousel
Logo
Loader
Lightbox
Login Form
Modals
OTP Verification Form
Popular Notes
HTML
CSS
JavaScript
SQL
Services
About
Contact Us
Ui Code
Snippets
Zoom an Image on Mouse Hover Using HTML, CSS and javaScript
HTML
CSS
JS
Output
HTML
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>Zoom an Image on Mouse Hover Using HTML, CSS and javaScript</h1> <p>Mouse over the image:</p> <div class="mainContainerDiv"> <img id="imageTagId" src="https://www.teknowize.com/attachments/file_1663012514.jpg" width="300" height="240"> <div id="ZoomResult" class="result-of-zoom"></div> </div> </body> </html>
CSS
body { display: flex; align-items: center; justify-content: center; flex-direction: column; } h1{ text-align:center; } .mainContainerDiv { position: relative; } .zoom-with-lense { position: absolute; border: 1px solid #d4d4d4; width: 40px; height: 40px; } .result-of-zoom { border: 1px solid #d4d4d4; width: 300px; height: 300px; }
JS
function imageZoom(imgID, resultID) { var img, lens, result, cx, cy; img = document.getElementById(imgID); result = document.getElementById(resultID); lens = document.createElement("DIV"); lens.setAttribute("class", "zoom-with-lense"); img.parentElement.insertBefore(lens, img); cx = result.offsetWidth / lens.offsetWidth; cy = result.offsetHeight / lens.offsetHeight; result.style.backgroundImage = "url('" + img.src + "')"; result.style.backgroundSize = (img.width * cx) + "px " + (img.height * cy) + "px"; lens.addEventListener("mousemove", moveLens); img.addEventListener("mousemove", moveLens); lens.addEventListener("touchmove", moveLens); img.addEventListener("touchmove", moveLens); function moveLens(e) { var pos, x, y; e.preventDefault(); pos = getCursorPos(e); x = pos.x - (lens.offsetWidth / 2); y = pos.y - (lens.offsetHeight / 2); if (x > img.width - lens.offsetWidth) { x = img.width - lens.offsetWidth; } if (x < 0) { x = 0; } if (y > img.height - lens.offsetHeight) { y = img.height - lens.offsetHeight; } if (y < 0) { y = 0; } lens.style.left = x + "px"; lens.style.top = y + "px"; result.style.backgroundPosition = "-" + (x * cx) + "px -" + (y * cy) + "px"; } function getCursorPos(e) { var a, x = 0, y = 0; e = e || window.event; a = img.getBoundingClientRect(); x = e.pageX - a.left; y = e.pageY - a.top; x = x - window.pageXOffset; y = y - window.pageYOffset; return { x: x, y: y }; } } imageZoom("imageTagId", "ZoomResult");
Output