How to stagger line indentation with vanilla Javascript.

Imagine you need to create a template with dynamic text fields (editable by a non-developer), with line indentations that increase for each new line, to follow an offset background image. Here's one way to do it

Last updated on 30 January, 2019, 9:08am by keston

Preface

As part of a recent banner build, I came across an unusal requirement to have, 1) partially editable live text (not dynamic on a feed), 2) the text in question also needed to increase indentation after each line break, to follow a background element, 3) any edits to this code were intended to be carried out by a non-developer - so the solution needed to be somewhat straightforward. 

 

The code in the supplied masters used a series of      placements to pad each line. While this did work, I wanted to do something a bit easier to maintain/edit - plus avoid having to count the spaces (I'm that lazy), hence the following technique.

Quick CodePen
                        
                        
How It Works

In this example, the data-spacing attribute is used to set the 'indentation'.

 

0 - gives no indentation and there is no max indentation. Any whole number above 0 will indent the text. Go as wild as your screen is wide! Try it on Codepen.

 

Note: For the banner project I worked on, the background element's 'slope' (the yellow area) was different for various formats so there needed to be a way to set the steepness of the indentation per format.

 

I have put some comments in the JS to explain some parts in a bit more detail.

Use Cases

This is a fairly rare requirement, however - if you ever find yourself smashing out multiple   to position text around a background pattern - here's a way you could get around that.

 

Hope this helps,

Keston