2
votes

I'm writing a simple jQuery plugin that displays images with a specific class in the center of the screen (when clicked, full-sized). I am using this html code, where my image is displays:

<div id="source">
   <img src="" alt="" />
</div>

In "src" attribute I place path to full-sized image, wait for onload event where I make some animation with jQuery:

$("#source img").load(function(){
var calcWidth = this.width + ...
}); 

But in Google Chrome (and only in Google Chrome) when onload event fires, this.width is equal to previous image's width. This means that when I first time set "src" to "img/1.jpg" with 800px width, all is ok, but when I try to set second image "img/2.jpg" in "src" with 600px width, this.width still returns 800px (in onload event!).
how to explain this behavior?

UPD:
I set src in this way:

function NavClick(){
        $("#source img").attr({
            src: $(this).attr("src")
        });
        currentImage = this.indx;
    }

"this" is referenced to the thumbnail image, I use the same src for thumbnail and full-sized image for test only, later I will place their in different directories.
This code solve my problem, but I don't exactly understand why:

function NavClick(){
        $("#source img").attr({
            src: "#"
        });
        $("#source img").attr({
            src: $(this).attr("src")
        });
        currentImage = this.indx;
    }

Before setting new src I set it to "#", perhaps this is due to caching images, but appears only in google chrome.

1
Use $(this).width() to read the current image width inside the jQuery handler.Shadow Wizard Is Vaccinated V3
$(this).width() returns value equal to this.widthKai
I hope you do not have the img src="" when the page load, empty src attribute for an image means the source is the same url as the one which load the current page (can be a POST or a GET), set at least "#" in the SRC attribute you will save hours of debugging.regilero
@regilero, thanks, I corrected itKai
Well, from quick test (jsfiddle.net/yahavbr/9xxUz) it does work fine in Chrome - how do you set the image src?Shadow Wizard Is Vaccinated V3

1 Answers

0
votes

Use window load event, the image is not fully loaded on the image load event (see this question)

I didn't test it, but this might just do the trick, let me know if it doesn't (or if it does)

$(window).load(function(){    
    var calcWidth = $("#source img").width() + ...;
});