Cheesey_memes
Cheesey_memes

Reputation: 1

How would I make this function repeat continuously?

I'm making a small website and I'm trying to make two elements repeatedly hide and show so it'll look like it's switching between the two. I have a draft code that would do that but I'm not sure how to make it loop.

    function MyDraft(){
  var x = document.getElementById("one");
  var y = document.getElementById("two");
  if (y.style.display === "none"){
    x.style.display = "none";
    y.style.display = "block";
  }
  else {
    x.style.display = "block";
    y.style.display = "none";
  }
}

Upvotes: 0

Views: 47

Answers (2)

Andy
Andy

Reputation: 63524

If you use classes you can toggle an element having an hidden class (which sets visibility: hidden). Then just add the code that does the toggling for the elements inside setInterval.

// Cache the elements
const boxes = document.querySelectorAll('.box');

// Iterate over the elements toggling their
// `hidden` class
setInterval(() => {
  boxes.forEach(box => box.classList.toggle('hidden'));
}, 1000);
.box { width: 30px; height: 30px; background-color: lightgreen; }
.hidden { visibility: hidden; }
<div class="box"></div>
<div class="box hidden"></div>

Upvotes: 2

ControlAltDel
ControlAltDel

Reputation: 35051

Just use setInterval

    function MyDraft(){
  var x = document.getElementById("one");
  var y = document.getElementById("two");
  if (y.style.display === "none"){
    x.style.display = "none";
    y.style.display = "block";
  }
  else {
    x.style.display = "block";
    y.style.display = "none";
  }
}

var interval = setInterval(myDraft, [timeInMilliseconds]);

Save the interval variable somewhere so you can later call clearInterval if you want

Upvotes: 1

Related Questions