Reputation: 139
I'm trying to make a webpage. But I have a problem with rotating strings.
I want to make several strings to rotate when the page is loaded.
If there is only one string, it rotates well with this code.
But when there are two or more strings and I give them the same class
to rotate with equivalent JavaScript code, it's not working.
It's working(Only the first string)
<body>
<div>
<ul>
<li><span id="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span>
</li><p>
<!--<li><span class="div" style="background-color:skyblue">the
most unique cocktails in Singapore</span></li>-->
</ul>
</div>
<script>
var div = document.getElementById("div");
var timer = setInterval("doRotate()",200);
div.onclick = function (e) {
clearInterval(timer);
}
function doRotate() {
var str = div.innerHTML;
var firstChar = str.substr(0,1);
var remains = str.substr(1, str.length-1);
str = remains + firstChar;
div.innerHTML = str;
}
</script>
</body>
and this is not working
<body>
<div>
<ul>
<li><span class="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span></li><p>
<li><span class="div" style="background-color:skyblue">
the most unique cocktails in Singapore</span></li>
</ul>
</div>
<script>
var div = document.getElementsByClassName("div");
var timer = setInterval("doRotate()",200);
div.onclick = function (e) {
clearInterval(timer);
}
function doRotate() {
var str = div.innerHTML;
var firstChar = str.substr(0,1);
var remains = str.substr(1, str.length-1);
str = remains + firstChar;
div.innerHTML = str;
}
</script>
</body>
I want to see those two strings are rotating at one time. Please tell me the error that I'm making... Thank you!
Upvotes: 0
Views: 55
Reputation: 273710
document.getElementsByClassName("div")
will return an object of many divs and not a single div so you need to iterate on them like this :
var div = document.getElementsByClassName("div");
var timer = setInterval("doRotate()", 200);
for (var i = 0; i < div.length; i++) {
div[i].onclick = function(e) {
clearInterval(timer);
}
}
function doRotate() {
for (var i = 0; i < div.length; i++) {
var str = div[i].innerHTML;
var firstChar = str.substr(0, 1);
var remains = str.substr(1, str.length - 1);
str = remains + firstChar;
div[i].innerHTML = str;
}
}
<body>
<div>
<ul>
<li><span class="div" style="background-color:yellowgreen">
What to eat at Newton Food Centre</span></li>
<p>
<li><span class="div" style="background-color:skyblue">
the most unique cocktails in Singapore</span></li>
</ul>
</div>
<script>
</script>
</body>
Upvotes: 1