I am trying to implement Lighbox effect on click of a Image using below code
document.addEventListener('click',function(){
var target = event.target || event.srcElement;
if(target.className == "acv"){
var id = target.id, src= target.src,
type = target.nodeName, imgW, imgH,
temp = document.createElement('div'),
sHeight = screen.availHeight,
sWidth = screen.availWidth,
st = temp.style;
var img = new Image();
img.onload = function(){
imgW = this.width;
imgH = this.height;
}
img.src = src;
var imgH = ( sHeight >= imgH + 20 ? imgH : (sHeight - 20) );
var imgW = ( sWidth >= imgW + 20 ? imgW : (sWidth - 20) );
img.style.height = imgH;
img.style.width = imgW;
img.style.position = "relative";
img.style.left = ( (sWidth - imgW) / 2 ) + "px";
img.style.top = ( (sHeight - imgH) / 2 ) + "px";
temp.appendChild(img);
temp.id = "lightbox";
st.width = sWidth + "px";
st.height = sHeight + "px";
st.backgroundColor = "Gray";
st.zIndex = 123;
st.position = "absolute";
st.top = st.left = 0;
st.margin = "0 auto";
document.body.appendChild(temp);
}
});
Please check the working fiddle here.
And I feel like I have done something wrong in this. Please correct and help me to improve the code.
Seems, if image already loaded onload event not fires, also it is mistake to try to use ImgW and ImgH initialised in event body to use outside of scope of event handler, at least, you shold also “fix” img in event handler, so far here the code which work fine for the fiddle:
also i would to use window width/height for calculate positions.