Get the width in pixels of a Dynamic text string

While writing some code for a Ticker Tape, I wanted to just use the hypeDocument.setElementProperty() API to move the left position of the element that contains a dynamic length string.

This seems simple enough until you pay attention to that word dynamic. Which means if we populate the Ticker Tape element’s innerHTML with a string that may change we may fall short of the correct left position or go too far.

So here is the trick to get the width of a string.

The trick is to place the string within <span></span> tags and make sure the string forms into a single line with no text wrap, which can be simply done with the css white-space:nowrap!important;

The span will expand or contract depending on the length of the string.
The css part is optional depending on what you are trying to do. If we do have wrapped text then we will get the wrapped width and not the full string width.


Example :

In the head I add css style for no wrap.

<style>
        .ticker {
        	white-space:nowrap!important;
          }
</style>

When we add the string here held in a var named description , we enclose the string in span tags. We also give the span an id so we can access it later on.

    ticker.innerHTML = '<span id=\'tickerSpan\'>' + title + ' : ' + description + '<\span>' ;

We can now get the width of the span which holds the string by getting the span element’s .offsetWidth

var spanWidth = document.getElementById('tickerSpan').offsetWidth

Now all we need to do is move left using that width.

hypeDocument.setElementProperty(ticker, 'left', -(spanWidth), tickerTimeDuration, 'linear')


3 Likes

A slight update to this and which may save you messing with a span.

If you can use a Hype text element instead of a rectangle element then you just need to set the nowrap on the text element.

The text element will then act just like the span contract and expand. The nowrap will keep it in a single line and the offsetWidth will be what ever the text element has exapnded/contracted to

1 Like