0

my name is Ezequiel, I'm new with JQuery

I want to dynamically change the src of an and get the width of the image that it's displayed.

I have an img tag, with an ID ("idImg").

The problem is that my code works only for the first src change, and I have to change it multiple times (iterative), but I'll show you with only 2 hardcoded changes.

      $("#idImg").attr("src", scrString); //src field changes ok
      alert($("#idImg").width()) // ok, this is the real width.
      $("#idImg").attr("src", scrStringANOTHER); //src field changes ok
      alert($("#idImg").width()) // nope, it keeps the same width than the last one.

I don't know, just cannot find out what the problem is

EDIT: I know I have to wait until it loads, but that doesn't work if I change the src multiple times. I need to change the src multiple times, and check the resulting width of each image.

Any help?

Ty very much

Ezequiel.

Eze Barnes
  • 57
  • 2
  • 8

2 Answers2

0
$("#idImg").load(function()
{
  alert($(this).width());
});

Bind to the load event of the image, at which point the width will be ready.

Another way of going about this is to load the image in a different img then swap it out after load. See this SO thread on preloading images: Preloading images with jQuery

Community
  • 1
  • 1
Eli Gassert
  • 9,745
  • 3
  • 30
  • 39
  • Yep, I've tried the load event.. It prints the 1st one, and not the others. I have to declare it once, right?, it will go there every time I change the src – Eze Barnes Feb 28 '13 at 20:28
0
$(document).ready(function(){ 
    $('#idImg').on('click', function() {
      $(this).attr('src', 'newimage.png');  
    }).load(function() { alert(this.width); });
});

See full example: http://jsfiddle.net/k9rn7/

bighead.dev
  • 176
  • 1
  • 8
  • That works, but the problem is that I need to change the src multiple times and obtain the multiples "widths". I mean, every time I change the src (I have an array of "src strings"), I want to know the width of that image. How can I do that? – Eze Barnes Mar 01 '13 at 16:26