Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Trino Mitra
11,165 PointsHow to change the content in a html header every couple of seconds?
I want my webpage to change the content of the header after every time interval. I have a javascript array with the different headers in it and would like to change between the items in the array. How do I properly use the setInterval javascript function to accomplish this?
Trino Mitra
11,165 PointsHere is the code: <script type="text/javascript"> function doSomething(){ var aa= ['Cat' 'Dog' 'Cow' 'Fish'] ;
while (i < aa.length) {
document.getElementById("demo").innerHTML = aa[i]; setInterval(function(){ i=i+1; }, 1000);
}
}
</script>
2 Answers
Bob McCarty
Courses Plus Student 16,618 PointsTrino, Assign the window.onload to an anonymous function. This function contains the function that alters the header content, and the setInterval call.
window.onload = function() {
var interv = 0; // setInterval return value.
function change_header(){
// header change content logic here;
};
// check the interv value
if (interv === 0 ) {
//call setInterval with your timeout value here 8000
interv = setInterval(change_header, 8000);
};
} // end anonymous function
Steven Parker
243,318 PointsI'm feeling pretty sure this is covered in a course here, but since I don't have a ready reference, here is some sample code that does what you describe. Note that you do not want to call setInterval in a loop - it IS a loop:
var headers = ["First Header", "Next Header", "Another Header", "Last One"];
var lastheader = -1;
function newHeader() {
if (++lastheader >= headers.length)
lastheader = 0;
document.getElementById("myheader").innerText = headers[lastheader];
}
newHeader();
setInterval(newHeader, 2000);
<h1 id="myheader">headers will go here</h1>
Chyno Deluxe
16,936 PointsChyno Deluxe
16,936 Pointscan you provide your code.