0

Here is my code

const p = document.getElementById("looper");
function shiftright() {
    let temp = new String();
    for(var i = 1; i < p.textContent.length - 1; i++)
    {
        temp[i] = p.textContent[i-1];
    }
    temp[0] = p.textContent[p.textContent.length-1];
    p.textContent = temp;
}
window.setInterval(shiftright, 1000);

Whenever I run it the text within the element disappears once the interval expires. I am trying to make the text loop around.

  • 1
    Please add a [mre]! But it probably has to do something with overriding the content. – 0stone0 Jan 20 '22 at 12:59
  • A couple of things: 1. The text content of a string in JavaScript is **immutable**. You can't modify the text of a string; you can only create a new string with new text based on the old. 2. There's basically never any reason to use `new String` in JavaScript. It creates a string object, but most of the time you're dealing with string primitives. More about strings [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String). – T.J. Crowder Jan 20 '22 at 13:02
  • So instead of `let temp = new String();`, you want `let temp = p.textContent[p.textContent.length-1];`. Instead of `temp[i] = p[i-1];`, you want `temp += p.textContent[i-1];` (Note that you missed out the `textContent` part there.) (Get rid of the `temp[0] = ...` entirely.) But there's a much better way than the loop: Use [`substring`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring). – T.J. Crowder Jan 20 '22 at 13:03
  • Basically: `const oldText = p.textContent; const newText = oldText[oldText.length - 1] + oldText.substring(1); return newText;` (Or in modern environments, you could start with `const newText = oldText.at(-1);`.) – T.J. Crowder Jan 20 '22 at 13:05

0 Answers0