I'm new to coding. I want to write a JS program to rotate a string (in the right direction) periodically by removing the last character every time and attaching it to the front. But when I run my code, a whole line or the whole page will be filled with the string. What's wrong with my code?
I defined a function that: 1. stores the content of an HTML p element in a variable; 2. changes the value of the variable to a new string with the last character of the original string attached to its front; 3. changes the content of the p element into the new string, and 4. repeats this process using the setInterval method.
function animation() {
var text = document.getElementsByTagName("p")[0].innerHTML;
setInterval(function() {
text = text.substring(text.length - 1, 0) + text.substring(0, text.length - 2);
document.getElementsByTagName("p")[0].innerHTML = text;
}, 100);
}
<body onload="animation()">
<p>JavaScript</p>
</body>
I believe your problem is just a slight misunderstanding in how the substring functions works: text.substring(text.length - 1, 0)
doesn't necessarily make much sense because the start point is after the end point. In this case it just ends up being equivalent to text.substring(0, text.length - 1)
which explains why your text keeps getting larger and larger.
Replacing text.substring(text.length - 1, 0)
with text.substring(text.length - 1, text.length)
should do the trick, and hopefully it's obvious why this gets the last letter. Also, the end index is non-inclusive, meaning the substring doesn't include the character at the index, so you'll want to replace text.substring(0, text.length - 2)
with text.substring(0, text.length - 1)
As a side note, instead of using text.substring(text.length - 1, text.length)
to get the last character, you could just use text[text.length - 1]
to get it, which I think is a bit cleaner.
Here's a working code snippet with the changes mentioned:
function animation() {
var text = document.getElementsByTagName("p")[0].innerHTML;
setInterval(function() {
text = text[text.length - 1] + text.substring(0, text.length - 1);
document.getElementsByTagName("p")[0].innerHTML = text;
}, 100);
}
<body onload="animation()">
<p>JavaScript</p>
</body>
To make sure you get how everything works I would try and see if you can get it to roll/rotate the other way