Ad

Function Works For NON Dynamically Loaded Images

- 1 answer

FIDDLE: https://jsfiddle.net/m2barfho/

Hi I have the following function:

  var imgs = $('img');
  if ($(imgs).hasClass('cboxPhoto')) {
    imgs.each(function() {
      var img = $(this);
      if ($(img).width() > 1000 && $(img).height() > 1000) {
        img.addClass('relative');
      } 
      else {
        img.removeClass('relative');
      }
    });
  }

I am essentially stating if an <img> has the class of "cboxPhoto" then run the each() function to add the class of "relative" if the image width is greater than x it's height is greater than x. This function works fine when the HTML is already statically placed in. However, these images are dynamically generated, I've tried

$('#body').load('index.html #cboxLoadedContent', function() {
}

and

$(document).ready(function () {} with .`load`

also tried adding an .on event listener, even though I was not using binding events to see if when it is loaded it might detect.

THE PROBLEM: The images are dynamically generated via an upload module, and not statically placed in. Colorbox for some reason will not run my function. The images have the class .cboxPhoto. How can I have my hasClass function detect a dynamically generated image, and run the preceding each() function? It works in my fiddle, but not my index?

Ad

Answer

You can select the images based on if they have the cboxPhoto class, then loop through them.

var imgs = $('img.cboxPhoto');
imgs.each(function() {
  var img = $(this);
  if (img.width() > 1000 && img.height() > 1000) {
    img.addClass('relative');
  } else {
    img.removeClass('relative');
  }
});

Fiddle

Ad
source: stackoverflow.com
Ad