Hi everybody!
I wanted to share a neat little JavaScript snippet I worked on during my first YouTube live stream. The goal was to clip a block of text to a specific number of lines and add a “Read More” link (or anything else, as the current project requires) at the end if the text exceeds that limit—in the same block, not as a separate button.
The History
The project, which I can’t name just yet, used a previous version of this function. How did it work?
- It split the text into separate characters.
- Placed each and every single one into a
<span>
. - Used
forEach
on the spans and checked if theoffsetTop
of that span changed—if it did, it’s a new line.
I don’t know where my head was when coding this—not on my shoulders, that’s for sure.
Amazing New Solution!
Frankly, it’s nothing that hasn’t been done before.
But it works.
And it’s Elegant!
How It Works
In short, it checks added characters in a loop, starting with a single character plus the appendage, and if the block’s height is higher than before, it’s a new line.
As I said, elegant! I love this new solution.
And I kept that Observer, because why not, right?
Fun Fact
I asked ChatGPT to write a dark sci-fi story. Haven’t read it, yet. Honestly – I can’t wait to get to that!
Come Hang Out Next Time
The YouTube live stream was an interesting experience. I liked it a lot!
Check the stream here: https://youtube.com/live/FBpU7P3o5ME
Thank you for reading!
Source link
lol