Skip to content

JavaScript translate depending on index

So I have a code like this

const letterPosition = () => {
    const letters = document.querySelectorAll('.txt li');
    letters.forEach((letter, index) => {
        letter.setAttribute('style', 'transform:translateY((index * 10)vh)');

and it doesnt work… Any solutions? (i want to change each letter position depending on array index)


You are not referencing the index variable correctly, your style attribute is always the same. Also the parenthesis in translateY are not necessary. Depending on your runtime you can try template strings

letter.setAttribute('style', `transform:translateY(${index * 10}vh)`);

or string concatenation

letter.setAttribute('style', 'transform:translateY(' + (index * 10) + 'vh)');