jquery - .height() .width() doesn't adjust to change in size -


i have image adjusts screen size .height , .width() doesn't adjust, leaving margin-left , margin-top changing. there way make adjust?

    var $src = $(this).attr("href");     $('#overlay').append('<img class="image" src="' + $src + '" />');      var $image = $('img');     $('.image').css('max-height','80%');     $('.image').css('max-width','90%');     $('.image').css('position', 'fixed');     $('.image').css('top', '50%');     $('.image').css('left', '50%');     var $height = $image.height();     var $width = $image.width();     $('.image').css('margin-top', (($height/2)*-1));     $('.image').css('margin-left', (($width/2)*-1));  

http://jsfiddle.net/a8a4y/

the problem image isn't loaded when messure it. height, width zero.

http://jsfiddle.net/w8snw/

so can add handler load event , when fired execute code:

var $src = $(this).attr("href"); $('#overlay').append('<img class="image" src="' + $src + '" />');  var $image = $('img'); $image.on("load",function(){ // new stuff, listen load event                               // fired when image loaded , size                              // size known     var $height = $image.height();    var $width = $image.width();    $('.image').css('margin-top', (($height/2)*-1));    $('.image').css('margin-left', (($width/2)*-1));     console.log("height: " + $height);    console.log("width: " + $width); }) 

i included example more optimized code. example every time use selector javascript search in dom element. should once, have at: http://jsfiddle.net/w8snw/2/


Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -