Skip to content
Advertisement

Retrieve naturalWidth of updated image src

$(".photo").on('click', function(){
    this.src = this.src.replace(/thumb/g, 'original');
    alert(this.naturalWidth);
}

I am using jQuery in Rails4 to update the src attribute of an image. I am also using paperclip for image uploading.

The flow: when I click the image in the first time, it returns the thumb width(140px). However, the subsequent clicks return the natural width of the original image(1200px).

Is it possible to get the natural width of the original image in the first time?

Advertisement

Answer

Wait for the image to be loaded. onload handler will be invoked when image has finished loading

This event will fire every time src property of the image is changed.

Try this:

$(".photo").on('click', function() {
      this.src = this.src.replace(/thumb/g, 'original');
      var img = new Image();
      img.onload = function() {
        alert(this.naturalWidth);
      }
      img.src = this.src;
    }
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement