I am dynamically resizing some boxes, and this functionality is placed inside my Images module. It works well, but since these boxes are present only on one part of the website, it throws me an error that it can't read the height property of undefined, which is obvious because the bundled file fires the window.resize but does not find the boxes, which blocks my other functionalities/modules.
So my question would be - is there a way to fire this resize event only if there are elements on the page that meet the certain class/id's (for example .box-image)... with some kind of conditional statement?
Many thanks for all possible hints.
EDIT: It throws error two times, first time because of the height property in the constructor, since this sets the initial height just after the reload.
class Images {
constructor() {
//make boxes same size as images initally and on resize
var images = $('.box-image');
var imageHeight = images[0].height;
var boxes = $('.content-box');
$(boxes).css({'height': imageHeight + 'px'});
this.events();
}
events() {
$(window).resize(function() {
var images = $('.box-image');
var imageHeight = images[0].height;
var boxes = $('.content-box');
if(images.length > 0) {
$(boxes).each(function (i, element) {
$(element).css({'height': imageHeight + 'px'});
});
}
});
}
}
An easy check before using the variable:
if (images && images.length > 0) { .. }
class Images {
constructor() {
//make boxes same size as images initally and on resize
var images = $('.box-image');
if (images && images.length > 0) {
var imageHeight = images[0].height;
var boxes = $('.content-box');
$(boxes).css({
'height': imageHeight + 'px'
});
this.events();
}
}
events() {
$(window).resize(function() {
var images = $('.box-image');
if (images && images.length > 0) {
var imageHeight = images[0].height;
var boxes = $('.content-box');
$(boxes).each(function(i, element) {
$(element).css({
'height': imageHeight + 'px'
});
});
}
});
}
}
Bring your var imageHeight = images[0].height; into your if statement like this
class Images {
constructor() {
//make boxes same size as images initally and on resize
var images = $('.box-image');
var imageHeight = images[0].height;
var boxes = $('.content-box');
$(boxes).css({'height': imageHeight + 'px'});
this.events();
}
events() {
$(window).resize(function() {
var images = $('.box-image');
var boxes = $('.content-box');
if(boxes && images.length > 0) {
var imageHeight = images[0].height;
$(boxes).each(function (i, element) {
$(element).css({'height': imageHeight + 'px'});
});
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With