Magnify an HTML element
July, 2021
Introduction
Sometimes we will need to magnify(zoom) an element in html when mouseover it. One solution to achieve this is creating a clone for the element that we want to magnify. Then scale the cloned one and show the corresponding magnified area. Here is an example:
Step 1: Define a table in HTML
<div class='area'></div>
<div class='zoomed'></div>
Step 2: Define CSS classes
.area{
width: 200px;
height: 300px;
overflow:hidden;
border:1px solid gray;
color:white;
text-align:center;
padding:10px;
display:relative;
float:left;
}
.zoomed{
width: 300px;
height: 200px;
overflow:hidden;
border:1px solid gray;
left:250px;
position:fixed;
}
Step 3: Define a javascript function
function zoomIt(e){
//get the area element an clone it
var itm = document.querySelector('.area');
var cln = itm.cloneNode(true);
//remove events and scale the cloned
cln.onmousemove = '';
cln.onmouseup = '';
cln.style.transform = 'scale(3)';
cln.style.transformOrigin = '0 0';
//clean the zoom area and append the cloned
document.querySelector('.zoomed').innerHTML = '';
document.querySelector('.zoomed').appendChild(cln);
//get the current coordinates of your mouse
e = e || window.event;
pos3 = e.clientX;
pos4 = e.clientY + window.pageYOffset;
//get the width and height of zoomed
var cx = document.querySelector('.zoomed').offsetWidth / 2;
var cy = document.querySelector('.zoomed').offsetHeight / 2;
//scroll the zoomed area to the corresponding position
document.querySelector('.zoomed').scrollTo(pos3*3-cx , pos4*3-cy);
}
Check a working demo for this code: