JSFiddle - React, Tailwind, and code Playground
by csaltyj
HTML
<img class="zoom-img" src="http://placekitten.com/800/800" width="200" height="200" /><br />
<img class="zoom-img" src="http://placekitten.com/1200/500" width="200" height="83" /><br />
<img class="zoom-img" src="http://placekitten.com/1300/1300" width="200" height="200" />
<div id="loupe"><img src="" /></div>
CSS
#loupe {
cursor: none;
display: none;
position: fixed;
left: 0px;
top: 0px;
width: 160px;
height: 160px;
border: 4px solid #999;
background: #000;
overflow: hidden;
}
#loupe img {
position: absolute;
}
.zoom-img {
cursor: none;
}
JavaScript
/* Loupe */
// Turn on loupe
$('.zoom-img').mouseenter(function(e) {
$('#loupe img').attr('src', $(this).attr('src'));
$('#loupe').css({
left: e.pageX - $('#loupe').width() / 2,
top: e.pageY - $('#loupe').height() / 2
}).show().data('target', $(this));
});
$('.zoom-img, #loupe').mousemove(updateLoupeView);
function updateLoupeView(e) {
var $img = $('#loupe').data('target');
var imgTop = $img.position().top;
var imgLeft = $img.position().left;
var imgWidth = $img.width();
var imgHeight = $img.height();
if ($('#loupe img').width() == 0 ||
$('#loupe img').height() == 0)
return;
// Are we out of the image bounds? If so, hide the loupe
if (e.pageX < imgLeft || e.pageX > imgLeft + imgWidth ||
e.pageY < imgTop || e.pageY > imgTop + imgHeight)
{
$('#loupe').data('target', '').hide();
$('#loupe img').css({
left: 0,
top: 0
});
}
else {
var percX = (e.pageX - imgLeft) / imgWidth;
var percY = (e.pageY - imgTop) / imgHeight;
var zoomPosX = percX * $('#loupe img').width();
var zoomPosY = percY * $('#loupe img').height();
$('#loupe').css({
left: e.pageX - $('#loupe').width() / 2,
top: e.pageY - $('#loupe').height() / 2
});
$('#loupe img').css({
left: zoomPosX * -1 + ($('#loupe').width() / 2),
top: zoomPosY * -1 + ($('#loupe').height() / 2)
});
}
}