1

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);   
7
  • 3
    Put this line previousSkill.innerHTML = skills[counter]; in function Commented Sep 14, 2015 at 15:34
  • ... and another setTimeout too, or use setInterval instead, otherwise the function is executed only once. Commented Sep 14, 2015 at 15:35
  • yes, #anwerjunaid is right, otherwise skills[counter] will always display text1 as it's outside the function scope. Commented Sep 14, 2015 at 15:35
  • innerHTML is evil: stackoverflow.com/questions/395051/… Commented Sep 14, 2015 at 15:39
  • @Alex The post you've linked doesn't seem to support your disclaimer ...? Answers are introducing alternatives, and even defending innerHTML ("innerHTML is not evil at all"), but I can't find any proofs innerHTML being evil. Commented Sep 14, 2015 at 15:41

3 Answers 3

2

innerHTML is evil, use jQuery! (assuming because you have it selected as a tag)

Working fiddle

(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);
Sign up to request clarification or add additional context in comments.

1 Comment

Just a nit-pick: jQuery uses innerHTML under the hood, though they are using it correctly ; ).
0

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);

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.