Function works for NON dynamically loaded images
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?
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');
}
});
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM