i am trying to make a gallery viewer on which the webpage shows thumbs of the real images and then when the image is clicked, the original image(with original size) is displayed, the div which holds the html “img” element is changed to visible(else by default it is set to hidden) and meanwhile am trying to get the dimensions of the image so that i can center the images of different dimensions properly acc. to their width and the problem am having is that whenever i click any thumb for the first time after the page is loaded, the statement which gets the width of the image sends 0, and after that when clicking any other image without reloading the page (including the previous one) it shows the previous image’s dimension and sometimes it works and sometimes not(mostly doesn’t), please help me out. The javascript code is below.
// JavaScript Document
$(document).ready(function() {
$.post(
"loadup.php",
{
refer:"yes"
},function(response){
$("#gallery_view_tab").html(response);
initAll();
});
});
function initAll(){
$("<div id='imgViewer'></div>").appendTo("body"); //set up image viewer
$("#imgViewer").insertBefore("#monster_wrap"); //set before monster_wrap
var thumbimgs = $(".thumbimg");
for(i=0; i<thumbimgs.length; i++){
var thumbimg = thumbimgs[i].id;
var thumbid = '#'+thumbimg;
$(thumbid).click(loadImgviewer);
}
}
function loadImgviewer(){
var imgLink = this.getAttribute("data-link");
$("<img id='closeImgviewer' src='images/close.png' /><img src='' id='imgview' />").appendTo("#imgViewer");
$("#imgview").attr('src', imgLink);
$("#imgViewer").css('visibility', 'visible');
imgwidth = $("#imgview").width();
screenwidth = $(window).width();
var pos = (screenwidth - imgwidth)/2;
$("#log").html(pos);
$("#imgview").css('margin-left', pos);
$("#closeImgviewer").click(unloadImgviewer); //set click event handler on image view closer
}
function unloadImgviewer(){
$("#imgViewer").css('visibility', 'hidden');
$("#imgview").attr('src', '');
$("#imgViewer").empty();
}
I just rewrote your code a little.
Please try it our. Didn’t try it but I think it should work.