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
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.
In the head I add css style for no wrap.
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')