Example code: Html:
<div class="wrap">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="wrap">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="wrap">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
The css:
*{
margin: 0;
padding: 0;
}
.wrap{
width: 30%;
height: 200px;
background: #f7f7f7;
float: left;
}
.wrap:not(:first-child){
margin-left: 5%;
}
.item{
width: 100%;
height: 47px;
margin-bottom: 3px;
background: #999;
}
The js code that works:
(function($){
$('.wrap').each(function(){
var thisWrap = $(this),
naturalHeight = thisWrap[0].scrollHeight,
restrictedHeight = thisWrap[0].clientHeight;
if (naturalHeight - 5 > restrictedHeight){
thisWrap.css({'background': 'red'});
}
});
})(jQuery);
The js code that doesn't:
(function($){
function myCustomFunction(){
$('.wrap').each(function(){
var thisWrap = $(this),
naturalHeight = thisWrap[0].scrollHeight,
restrictedHeight = thisWrap[0].clientHeight;
if (naturalHeight - 5 > restrictedHeight){
thisWrap.css({'background': 'red'});
}
});
}
$(window).resize(function(){
myCustomFunction();
});
myCustomFunction();
})(jQuery);
In this codepen example both work, but on my test page when the code is in a function and invoked after the definition of the function it doesn't work.
The wrap
element is already on the page when the js loads, the js code detects for overflow, that css is defined in a file that gets loaded on line 39, the js gets loaded on line 1300+.
Putting all in a document ready function doesn't help.
How can this code in the same file work properly when not in a function?
EDIT: The issue seems to be with the window resize function, it seems that something is triggering that while the page loads.