I need some help writing a function with multiple if statements (unless there is a better method). I basically want to truncate text length based on window size. So if the viewport is less than 400px and the text length is greater than 35, then truncate using this method below...
$('option').each(function () {
var text = $(this).text();
if (text.length > 35) {
text = text.substring(0, 35) + '...';
$(this).text(text);
}
});
The function for window resize (basically combine above with below):
$(document).ready(function(){
if($( window ).width() < 400){
//do something;
}else{
//do something else;
}
});
$( window ).resize(function() {
if($( window ).width() < 400){
//do something;
}else{
//do something else;
}
});
Did a little more research and got it working with this code:
$(document).ready(myfunction);
$(window).on('resize',myfunction);
$('option').each(myfunction);
function myfunction() {
var text = $(this).text();
if (text.length > 35 == ($(window)).width() < 400) {
text = text.substring(0, 35) + '...';
$(this).text(text);
}
}
I wonder if/how a math function could calculate viewport width as a range and change truncation up to a maximum breakpoint?
I ended up answering my own question. So, I am posting it here incase someone else has a similar need or can improve what I have done...
Basically, I am truncating select option boxes by applying character length and window width. This prevents very lengthy option text to flow past its container and beyond the screen. I am sure there is a more efficient way to code this, but my tests appear to be successful which works for now.
/**
* Truncate lengthy option text in select boxes
*/
var defaultString=$('option').text();
function checkWidth() {
if($(window).width() > 600){
$('option').each(function(i){
len=$(this).text().length;
if(len>65)
{
$(this).text($(this).text().substr(0,65)+'...');
}
});
return false;
}
if ($(window).width() > 451 && $(window).width() < 599 ) {
$('option').each(function(i){
len=$(this).text().length;
if(len>50)
{
$(this).text($(this).text().substr(0,50)+'...');
}
});
return false;
}
if($(window).width() < 450){
$('option').each(function(i){
len=$(this).text().length;
if(len>35)
{
$(this).text($(this).text().substr(0,35)+'...');
}
});
return false;
}
}
checkWidth();
$(window).resize(checkWidth);
$(document).ready(checkWidth);
The last three lines bind 'checkWidth' and window 'resize' (which can also be 'width' or 'height') depending upon what you are achieving. Binding must be done before you can execute the function events.