Home Ask Login Register

Developers Planet

Your answer is one click away!

user3638239 February 2016

.load() not executed after page refresh

I'm trying to retrieve image dimensions after the page is loaded and if the view port size is modified. I can retrieve image dimensions after page load with .load but once the view port is modified, I haven't figured out how to retrieve the new image sizes.

I have written a function that is executed when the document is ready:

$(document).ready(ViewPortUpdate);  

When the viewport is modified, I'm calling the same function:

$(window).resize(ViewPortUpdate); 

The function is perfectly executed in both cases except for load events that are only triggered when the document is complete and not anymore if the viewport is modified.

Example:

function ViewPortUpdate()
{
console.log('view port updated');
$(".myimage").load(function()
    {
      // Here I retrieve the final image size 
      console.log('image loaded');
    }
}

when the page is loaded, I see 'view port updated' and 'image loaded' in my console but if I resize the window, I only see 'view port updated'. I suppose that the .load only work once and changing the view port size has no effect.

I'm probably not using the right approach but I don't know how to solve this issue.

Any idea?

Thanks Laurent

Answers


Arman Ozak February 2016

You can try this:

$(window).resize(function(){
   ViewPortUpdate();
   $('.myimage').trigger('load');
});

Important Note: I would recommend removing the part you get the image size from the load event and making it a separate function, instead of this.


Mission Mike February 2016

Possible solution:

$(window).on("load resize", function() {
  // retrieve image size
});

Because $(window).on("load", someFunction) triggers after all DOM content, including images, is loaded.

However if the window is resized before it's fully loaded, it probably can't grab all image dimensions. In which case, maybe:

$(window).on("load", function() {
  viewPortUpdate();
  $(window).on("resize", viewPortUpdate);
});

function viewPortUpdate() {
  // get image sizes;
}

Post Status

Asked in February 2016
Viewed 2,416 times
Voted 8
Answered 2 times

Search




Leave an answer


Quote of the day: live life