views:

50

answers:

1

Hello!

I have an image with mypic class

I'm using the load event to set the width and height of this image:

$(window).load(function() { 
    //Here I calculate final w and h  
    $('.mypic').css("width",w);
    $('.mypic').css("height",h);
    $('.mypic').height(h);
    $('.mypic').width(w);
});

In firefox I have no problem at all but in webkit browsers the height is not set and I don't know why. It's strange since the width is set without problems. Don't know what happens with safari and chrome. Am I missing something? Could anybody help me?

Thankyou very much.

A: 

Try

$(function() {
   //put your code here
  $('.mypic').css({
    'width': w,
    'height': h
  });
});

I'm doing a few thing here:

Encapsulating it all in a function and passing it to the jQuery object ($) will make sure it runs when the document loads (another handy use of $).

You can make one call to CSS with a JSON object of the attributes you want to set.

Oh, and setting the CSS height and calling .height(h) are identical except for their return value (http://api.jquery.com/height/) and, as you're not using the return value, you don't need to call both.

Anyways, tested and it works in Chrome and Safari.

EMMERICH
Ok!! I see what you say, but the piece of code where I write "//Here I calculate final w and h " needs to be executed once the page is loaded, with the image, because I get the actual width and height of the image before resizing it taking into account the width and height of the browser window... I copy paste the whole code if it helps.
$(window).load(function() { //Calculate values of height and width for the central image var totalWidth=$(window).width(); var totalHeight=$(window).height(); var sum= 510;//primary=248 + primaryRight=212 + margin=50 var maxWidth=totalWidth-sum; var maxHeight=totalHeight-30; var w=$('.slides2 img').width(); var h=$('.slides2 img').height(); if (w < h) { h = (h * maxWidth) / w; w = maxWidth; } else { w = (w * maxHeight) / h; h = maxHeight; } $('.mypic').css("width",w); $('.mypic').css("height",h); });
I've added a comment to the original code, just put your code there. As long as w and h are defined when you reach the css, it'll execute.
EMMERICH
Doing the way you say, using $(function() { ... If I put an alert(w); right after var w=$('.slides2 img').width(); I get 0 with safari...
"Wrong use of the load function" - [wrong](http://api.jquery.com/load/): `Note: The event handling suite also has a method named .load(). Which one is fired depends on the set of arguments passed.`
Pekka
@EMMERICH - His use of .load is **perfectly fine**.
meder
Yeah doing that. Updated my post as well although I hadn't seen load used like that. Thanks for the downvote xx
EMMERICH