Reputation: 1967
Simple while loop is not working properly. I write a script for limiting the text to 3 lines. It's very simple. I check if the height of the element (div) is higher than 3 lines (hardcoded font-size and line-height) and if so, I remove the last word and add ellipses. And I am doing it while string is shortly enough to fit on 3 lines.
It is working randomly, sometimes works, sometimes doesn't. If not working I have only 1 word on the 4th line. So it skips only the final iteration and not every time.
$('div.prod-description').each(function(){
var obj = $(this);
if(obj.height() > 60) { // line-height: 18px;
var ellipses = '...';
var new_text = null;
while(obj.height() > 60) {
new_text = obj.text().slice(0, obj.text().lastIndexOf(' '));
obj.text(new_text+ellipses);
}
}
});
I tried to remove the if statement
, I tried with do while statement
but it's the same.
EDIT: I found the problem! But don't know how to fix it. If I hit enter on the browser's address bar or I come to page from the menu it's working properly. If I refresh with F5
it's skipping the last iteration. Any ideas?
Upvotes: 2
Views: 475
Reputation: 1967
After I was lucky to find that the script doesn't work properly only on refreshing the page with F5 I found the solution. https://stackoverflow.com/a/8310308/1333512
To correct this problem use:
$(window).load(function() {});
Out instead of:
$(document).ready(function() {});
Upvotes: 1