JSFiddle - React, Tailwind, and code Playground
by lollero
HTML
<div class="zoom">
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg" alt=""/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg" alt=""/>
<img src="http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg" alt=""/>
</div>
CSS
.zoom_wrap {
float: left;
position: relative;
z-index: 0;
overflow: hidden; /* Removing this will let the image flow outside the boundaries when zooming*/
margin: 20px;
}
.zoom_wrap img { display: block; }
.zoom_wrap .floater {
position: absolute;
top: 0;
left: 0;
display: none;
}
JavaScript
$(function() {
var zoom_lvl = 10;
// Find each img element inside .zoom...
$('.zoom img').each(function() {
var obj = $(this);
obj
// Wrap each of them with a parent div
.wrap('<div class="zoom_wrap">')
// Duplicate the original image.
// This will help keep the parent element from collapsing when the image is given position: absolute;
// Also, we don't have to force feed the parent div any dimensions this way...
.clone().insertAfter( obj )
// Differentiate the secondary image
.addClass('floater');
var zoom_wrap = obj.parent(),
floater = obj.next();
// On mouseenter and mouseleave...
zoom_wrap.on("mouseenter mouseleave", function( e ) {
// Checking the event type. This makes it a boolean value. Mouseenter: true or false.
var mouseenter = e.type === 'mouseenter',
objW = obj.width(),
animate = {};
// On mouseenter = image width + 2 times the size of zoom level
// On mouseleave = default back to image width
animate.width = mouseenter ? objW + ( zoom_lvl * 2 ) : objW,
// On mouseenter = minus zoom level
// On mouseleave = default back to zero
animate.marginTop = mouseenter ? -zoom_lvl : 0,
// On mouseenter = minus zoom level
// On mouseleave = default back to zero
animate.marginLeft = mouseenter ? -zoom_lvl : 0;
// The above variables define what properties to animate and which values to use.
floater.stop().animate( animate, 400);
});
});
});