Question

I have some tweets which are being pulled in on my website, each tweet length is different, but I want to make sure they get displayed on one line all the time.

This is how they should appear:

twitter string length

However, if the twitter length exceeds so many words it falls on to the next line and messes with the design.

My question here is to give this string or div? (Excuse my poor understanding) a max length? Then possibly if we reach the max string length to add a ellipsis (...) to the end of the string.

The idea in my head is something like if #div > 120 then shorten the string to 120 and add (...). Could someone help me make that happen? Not sure if javascript/jQuery is the way to go here? Thank you!

Était-ce utile?

La solution

You can simply use CSS to do that without moving into any computations either in JS or jQuery.

Define a fixed width to the div element where you want to display your tweet and apply css class Ellipsis to that element:

.Ellipsis
{
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

Hope that helps

Autres conseils

I would use the slice() method:

var formatted_tweet = long_tweet.slice(0, 120) + "...";

Or in function form:

function trim(str, len) {
    return(str.slice(0, len) + "...");
}

var formatted_tweet = trim(long_tweet, 120);

In Javascript you can use the substring method for this.

var value = "This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.  This is a very long tweet.";

function truncate(value, length){
   return value.substring(0,300);
}

alert(truncate(value,3000));

Working Example

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top