Preserve inner span tags when splitting text onto multiple lines

2 hours ago 1
ARTICLE AD BOX

I am attempting to build a parallax banner. The banner will contain a short text sentence that wraps onto multiple lines. But I need each line to perform individual animation. So my objective is to split the text onto however many lines is required to accommodate the width of the parent container. This container will change width depending on the screen size. I also need to update the results if the screen size changes - for example if a tablet is rotated.

So to summarise, if I have a paragraph in my parallax that says:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque fermentum sem magna, vitae pharetra neque</p>

I would want the results to output something like the below, with each span containing the maximum amount of words that can fit on one line:

<p> <span>Lorem ipsum dolor sit amet, consectetur</span> <span>adipiscing elit. Quisque fermentum sem</span> <span>magna, vitae pharetra neque<span> </p>

I have actually already achieved this by adding words to a span one at a time, and then creating a new span as soon as a word doesn't fit.

How to handle any HTML that is contained within the original text string? For example, if my text contained span tags as below:

<p>Lorem ipsum dolor <span class="my_class">sit amet, consectetur adipiscing elit. </span>Quisque fermentum sem<span class="my_class"> magna, vitae pharetra</span> neque </p>

I need the output to be valid HTML, so if the text within a span wraps onto multiple lines, each containing span will include an open and closing span tag. So my results would be:

<p> <span>Lorem ipsum dolor <span class="my_class">sit amet, consectetur</span></span> <span><span class="my_class">adipiscing elit</span>. Quisque fermentum sem</span> <span><span class="my_class">magna, vitae pharetra</span> neque<span> </p>

Everything I have tried fails spectacularly. Not even close. I don't even know what my approach would be, let alone how to code it. Does anyone have any idea how I could achieve this? I know there are loads of parallax libraries out there, but the end goal is so bespoke, I cannot find a library that would help too much.

Read Entire Article