views:

56

answers:

2

I have a block of jquery / javascript code that sets the left margin of an image depending on the browser width.

I do some sums to calculate the required left margin and it goes in var $diff.

This code works fine:

$('#background-wrapper>img').attr('alt',$diff);

which demonstrates that the sums are all working fine as the image ends up with the correct value for $diff inserted in its alt attribute. This works on IE, FF, Chrome.

But if I change the code to:

    $('#background-wrapper>img').css('margin-left',$diff);

then firefox and chrome work fine, using $diff as a value for the images left-margin as I intended, but IE throws a run time error and stops running the script, citing an Invalid Argument in jquery file. I'm using jquery 1.3.2.min.

Any ideas?

Heres the code for the full function.

function imageResizeCenter() {
  var $windowh = jQuery(window).height();
  var $windoww = jQuery(window).width();

  var imagesrc = $('#background-wrapper2>img').attr('src');

  var myimage = new Image();

  myimage.src = imagesrc;
  var $width = myimage.width;
  var $height = myimage.height;

  var $ratio = parseInt($width,10)/parseInt($height,10);

  var $newwidth = parseInt($windowh,10)*$ratio;

  var $diff = (parseInt($windoww,10)-parseInt($newwidth,10))/2;
  if($diff<0) $diff=0;
  $('#background-wrapper2>img').attr('height',$windowh).css('margin-left',$diff);

}
+1  A: 

Maybe

$('#background-wrapper>img').css('margin-left',$diff + 'px');
Harmen
+1. I would guess the lack of unit is an issue in some browsers.
KP
Thanks for the response guys. I've just tried all of those suggestions, and chrome / ff both seem happy with all of those vaients, but IE is still giving the same error- even if I just change the property to marginLeft.
Can you post your javascript code and markup, or a snippet of it?
KP
If you set the margin-left to a static value, does the error go away? Such as: $('#background-wrapper>img').css('margin-left','5px');
KP
yeah, the error goes away if I do that.
is it because ive used parseInt in the previous code but the .css function needs a string?
A: 

Using Javascript to set CSS properties has a little caveat: Instead of using dashes to separate multi-word properties, you use camelCasing. So margin-left should be marginLeft...

$('#background-wrapper > img').css('marginLeft', $diff);
Josh Stodola
Both dashed and camelCase version will work:"Also, jQuery can equally interpret the CSS and DOM formatting of multiple-word properties. For example, jQuery understands and returns the correct value for both .css('background-color') and .css('backgroundColor')." http://api.jquery.com/css/
KP