Introduction
Many a times, developers require to show larger popup images when users hover their mouse pointer over a thumbnail image. I will explain here a very simple JavaScript that can be used to show a popup image. The script is tested, and works fine in IE 7.0 and Mozilla Firefox 3.0.
Steps for the implementation
- Create a
DIV
named "imgbox
" on the HTML page on which your thumbnail images will be shown. The DIV
and the CSS element ID associated with the DIV
is shown below:
<div id="imgbox"></div>
The CSS element:
#imgbox
{
vertical-align : middle;
position : absolute;
border: 1px solid #999;
background : #FFFFFF;
filter: Alpha(Opacity=100);
visibility : hidden;
height : 200px;
width : 200px;
z-index : 50;
overflow : hidden;
text-align : center;
}
- Here is the JavaScript code to show the popup image:
- Get the left and top positions of the thumbnail image:
function getElementLeft(elm)
{
var x = 0;
x = elm.offsetLeft;
elm = elm.offsetParent;
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
elm = elm.offsetParent;
}
return x;
}
function getElementTop(elm)
{
var y = 0;
y = elm.offsetTop;
elm = elm.offsetParent;
while(elm != null)
{
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return y;
}
- Get the thumbnail image source, make the
DIV
visible, increase the height and width to the required size, and attach the image to the DIV
.
function Large(obj)
{
var imgbox=document.getElementById("imgbox");
imgbox.style.visibility='visible';
var img = document.createElement("img");
img.src=obj.src;
img.style.width='200px';
img.style.height='200px';
if(img.addEventListener){
img.addEventListener('mouseout',Out,false);
} else {
img.attachEvent('onmouseout',Out);
}
imgbox.innerHTML='';
imgbox.appendChild(img);
imgbox.style.left=(getElementLeft(obj)-50) +'px';
imgbox.style.top=(getElementTop(obj)-50) + 'px';
}
- Hide the
DIV
at mouse out.
function Out()
{
document.getElementById("imgbox").style.visibility='hidden';
}
- Add a
OnMouseOver
client-side event call for the thumbnail images to show the popup image on mouse-over.
<img id='img1' src='images/Sample.jpg' onmouseover="Large(this)" />
Comments
Hope this JavaScript would solve your popup image requirement. If you have implemented a popup image feature in some other way, or developed a feature-rich script, please put a link to your CodeProject article so that others can refer it too.