0

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";
  }
}
  • Does this answer your question? [Calling a function every 60 seconds](https://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) – Jeffrey Ram Sep 01 '22 at 18:14

2 Answers2

2

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>
Andy
  • 61,948
  • 13
  • 68
  • 95
1

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

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • How would I call on this to start once the site is opened? I know there's onload that I could use in the body element but would I be calling the function or something else? – Cheesey_memes Sep 01 '22 at 18:24
  • try using body.onload(function() { window.interval = setInterval(myDraft, [timeInMilliseconds])}()); – ControlAltDel Sep 01 '22 at 18:31