0

I want to center and crop images even for images that are dynamically loaded later.

HTML

<body>
    <div class="iThumbnail">
        <img src="images/art-vertical.jpeg" alt=""/>
    </div>
</body>

The body content above is static the first time. Later, body contents are loaded/replaced dynamically with other image sources.

So, for the static content, I'm able to center and crop the images with the below code (thanks to jonathanNicol and nickCraver).

$(document).ready(function() {
    function thumbnailImageCropCenter() {
        $('.iThumbnail').find('img').one('load', function() {
            if (($(this).height() > $(this).width()) && ($(this).height() != 0) ) {
                $(this).addClass('portraitView');
            }
        }).each(function() {
            if(this.complete) $(this).load();
        });
    }
    thumbnailImageCropCenter();
});

I want to avoid calling thumbnailImageCropCenter() every time I load a page content dynamically.

Question: Is there a way to automatically bind thumbnailImageCropCenter() to body such that it applies to all the images within body, no matter if images were loaded dynamically later.

PS: replacing .one() with .bind() didn't help.

Community
  • 1
  • 1
Kaya Toast
  • 5,267
  • 8
  • 35
  • 59

1 Answers1

1
$('body').on('load', '.iThumbnail img', function() {
  var $this = $(this);
  if (($this.height() > $this.width()) && ($this.height() != 0) ) {
       $this.addClass('portraitView');
  }
});
Latikov Dmitry
  • 956
  • 5
  • 8
  • Thanks. I get the concept. But `$('body').on('load', ....)` is not getting triggered, even if I put a `console.log` in it. Any suggestions please ? – Kaya Toast Mar 15 '15 at 13:21
  • I guess `$('body').on('load', ....)` isn't expected to work .. from http://api.jquery.com/on/ ... In all browsers, the load, scroll, and error events (e.g., on an element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event. – Kaya Toast Mar 15 '15 at 13:37
  • Yep, I have checked, it does not work( Some "bubble" issues with "load".. So I think your code is best option then. – Latikov Dmitry Mar 15 '15 at 13:54
  • You can try to track new HTML elements on the page - http://stackoverflow.com/questions/15268661/jquery-on-create-event-for-dynamically-created-elements – Latikov Dmitry Mar 15 '15 at 13:59
  • Thanks again for checking ... there seem to be some deprecation problem. Pity, there doesn't seem to be an elegant solution. – Kaya Toast Mar 15 '15 at 15:00