Reputation: 13
I am building a website and the homepage will basically have 2 div's containing text. I want one of the divs to change every 2 seconds with values I've placed in an array
var skills = ["text1","text2","text3","text4"];
var counter = 0;
var previousSkill = document.getElementById("myGreetingSkills");
var arraylength = skills.length - 1;
function display_skills() {
if(counter === arraylength){
counter = 0;
}
else {
counter++;
}
}
previousSkill.innerHTML = skills[counter];
setTimeout(display_skills, 2000);
Upvotes: 1
Views: 2008
Reputation: 7041
You need to wrap display_skills
inside a function in your setTimeout()
and use setInterval()
instead.
var myInterval = setInterval(function(){display_skills()}, 2000);
And make sure you call previousSkill.innerHTML = skills[counter];
inside your interval'd function - else it will run just once.
You can terminate your interval with window.clearInterval(myInterval);
Upvotes: 0
Reputation: 2401
Use array.join()
.
The syntax of this function is array.join(string), where3 string is the joining character.
Example:
[1, 2, 3].join(" & ")
will return "1 & 2 & 3"
.
Hope this helps,
Awesomeness01
Upvotes: -1
Reputation: 10216
innerHTML
is evil, use jQuery! (assuming because you have it selected as a tag)
(function($) {
$(function() {
var skills = ["text1","text2","text3","text4"],
counter = skills.length - 1,
previousSkill = $("#myGreetingSkills"),
arraylength = skills.length - 1;
function display_skills() {
if (counter === arraylength) {
counter = 0;
}
else {
counter++;
}
previousSkill.html(skills[counter]);
}
display_skills();
setInterval(function() {
display_skills();
}, 2000);
});
})(jQuery);
Upvotes: 2