2

I have a script that does images resizing on load:

$( document ).ready( function() {
  $( '.image' ).load( function() {
      // $(this).happens
   } );
} );

this seems to work fairly well with pages.

Now I am using ajax to get HTML elements, some of which might contains images that needs resizing, with the class "image". But the above snippet (when in the body of the ajax html) does not fire. Is there anyway to add this event somehow? I've tried ready(), but it fires before I can get the width/height. thanks

I also tried:

$( '.image' ).on( 'load', function() {
      // $(this).happens
} );
Timmy
  • 12,468
  • 20
  • 77
  • 107

2 Answers2

1

Your code will register callback functions to all images with class ".image" only upon initial page load. If you load some more images later on via AJAX request, those callbacks will not be registered and thus - resize won't happen.

If you need to register some callbacks for elements that are not yet present in DOM, you should use live() function from jQuery. That way you will be able to add more elements and have your callbacks being property registered for them.

Please refer to example and official jQuery live() documentation for details.

ŁukaszBachman
  • 33,595
  • 11
  • 64
  • 74
1

I'd do what this older post suggests. In your ajax callback run a trigger like trigger('images_loaded') and then do your resizing in a bind that's bound to the trigger

Community
  • 1
  • 1
Tin Can
  • 2,540
  • 2
  • 29
  • 39