views:

33

answers:

1

I have an image in a page that I am trying to get the width of.

<img class="zoomerIcon" src="zoomer.png" />

So I'm trying to get the width like this.

var imageWidth = $('.zoomerIcon').width();

However the value is 0 unless I set the width property in the tag.

Does width() only return a width greater than 0 if it's manually set in the property? You can see the whole script here.

http://www.wantedcreative.com/development/zoomer/index.html

Thanks

A: 

Update

Sorry, I should have looked at your source first. Here is how you need to change your code. The important thing to realize, is you can't get the width until the image has fully loaded. That is why I use a load event callback to retrieve the widths:

// Create the img element, add a load handler, then append it to the body
var $img = $('<img class="zoomIcon" alt="zoom icon" />').load(function(e){
  // get icon image properties for use with animation
  var imageWidth = $(this).width();
  var imageHeight = $(this).height();

  // ... any code that uses these variables needs to go in here ...

}).attr('src', zoomImage).appendTo( document.body );

Original Answer: This is general information.

You are probably putting this code in document.ready which will try to retrieve the width before the image has loaded. Try this instead:

$(window).load(function(){
   var imageWidth = $(".zoomer").width();
   alert( imageWidth ); // Should be correct
});
Doug Neiner
Doug that worked. The odd thing is in Firefox the original script seems to work Safari doesn't seem to be able to find the width.Any thoughts on what could be causing that?
acreek
Were you testing locally? Firefox's caching might be fast enough to load the image before your `width` code ran. Not really sure.
Doug Neiner