Rakesh M
3 min readNov 18, 2019

--

Truncate Text Based on length and show tooltip
using Plain Javascript and CSS

Good Bye ellipsis

Everybody should have come across a scenario where you should restrict the long text for the desired width. Else your design will be “BHOOM…!!!”

Yes, we do have a solution with CSS styles.

P {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;

}

The above snippet shows the text truncated using overflow property.

“Where is my Truncated text now?”

Yes where is the truncated text and how do you show your full text. You have to show the full text somewhere. But How?

Not necessary every time to show the complete text right!!

“Hmm…how about showing it only when the user needs to see it”
But how? That too without messing with the design?

Most of the UX/WireFrames/Prototypes Suggests using a “Tooltip” to show the Complete text. Sounds good right!!

But how do you do that? Thinking about jquery or any other libraries to import? No, not necessary.

Let’s create a tooltip to show on hover

We will just make this happen only using CSS.

Thinking how to handle hover events??
Is Javascript required for this??

The answer is a big “NO” for this.

Well, let’s start.

Let’s take a pretty long text inside a div.

But we need to show only some text inside the div with “…” right!!

So here is the required div with the text.

Now we need to show the full text on hover. So where do we have that?

Now let us write the CSS.

Now let us write CSS for hover.

And the final output will be like this.

That’s it. You can see the complete text on hover with a simple CSS code.

Below is the working example

Most of the cases you may need to handle the text dynamically. Based on the design you might need to truncate your text based on maximum character length.

You need to use a simple Javascript code and your job is done.

--

--