Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery.width return 0 on image

I'm using a code that looks like that:

img.load(function(){
    // do some stuff
    $(this).width();

});

In my callback the image size is always 0. It might have something to do with it but my images are locally loaded.

But in truth, if I do this.width, I will get the expected width and then I can do some kind of computation from here to change my extjs window.

After some tries, I realize that if I do $(this) all the attributes I changes don't seem to have any effect at all.

doing $(this).width(40); won't change the width of my image but doing this.width = 40 will change the width of my image. It's as if doing $(this) was copying my HTMLImageElement within a new element and those change would be applied only if I added to the dom again to replace the old one.

I'm not so sure to understand what's going on there.

Edit

This is what my img variable contains.

img = $('<img>');
img.attr('src', '....image');

Edit 2

This doesn't really change the fact that jQuery doesn't handle image size for in memory images but I felt it would be good for anyone using Extjs to not repeat my error. One of the big problem in my case is that the img object I used was a valid object but since I'm using ExtJs, I inadvertently made a stupid mistake. I created my window that way...

Ext.create('Ext.Window', 
  // some settings
  items: [{
      html: img.wrap('<div>').parent().html(),
  // etc

In other word, the event I created was on img, but I never really added img to the DOM. ExtJs added html text to the DOM which created a new object which can't be modified through event and so on.

So I do have to create an id to find the new element and all of this has to be done after a call to modalWindow.show() is done. After that everything works perfectly.

For resizing the window, if the dimensions are set, you can set them back to null and do a doLayout call on the window and it will recalculate windowsize.

like image 695
Loïc Faure-Lacroix Avatar asked Jun 27 '12 17:06

Loïc Faure-Lacroix


2 Answers

You found out that jQuery(this).width() does not work for images in memory. Choices are to use this.width/height or append it to the page and read it.

like image 179
epascarello Avatar answered Sep 22 '22 15:09

epascarello


I think you should try this...

 $("img").load(function(){
    // do some stuff
    $(this).width();

});

assuming you are using img tag only. in case if you have the id of img tag then, you should use for e.g. $("#idimg).load(fun...... contd.)

like image 45
Priyank Jain Avatar answered Sep 24 '22 15:09

Priyank Jain