Search code examples
javascripthtmljquerysettimeoutsetinterval

Need to render div one by one in 5 sec time interval in JavaScript


I want to render these divs one by one in a 5sec time interval when the second one renders the first div need to hide and this need to be cyclic process, I have tried some set interval but I couldn't able to achieve this please help me to achieve this.

Current Behaviour:

It has print directly like this

<div id="popup-wrap">
<div id="1" class='popup-wrap'>div one</div>
<div id="2" class='popup-wrap'>div two</div>
</div>

Please find my code below:

const myObject = {
    "1": {
      "eventJson": "<div>div one</div>"
    },
    "2": {
      "eventJson": "<div>Div two</div>"
    }
  }
};

  Object.keys(myObject).map(function (key, index) {
      getRenderhtml(myObject[key], key);

});

const getRenderhtml = (jsonHtml, key) => {
    var popup = document.createElement("div");
    popup.setAttribute("id", key);
    popup.setAttribute("class", "Popup");
    const html = jsonHtml.eventJson;
    popup.innerHTML = html;
    document.getElementById("popup-wrap").appendChild(popup);
    const element = document.getElementById(key);
    element.style.visibility = "none";
    element.style.opacity = "1";
    element.style.display = "block";
    element.style.position = "fixed";
  //   element.style.top = "0px";
    element.style.left = "10px";
  //   element.style.right = "0px";
    element.style.bottom = "10px";
  };

Thanks In Advance


Solution

  • Here's one way of doing this. Use setInterval to loop through, find the currently showing div, hide it and move on to the next, resetting to zero when we reach the end. This example is set to loop every second for demonstration

    const myObject = {
      "1": {
        "eventJson": "<div>div one</div>"
      },
      "2": {
        "eventJson": "<div>Div two</div>"
      }
    }
    
    // write the objects to the dom
    document.querySelector('#popup-wrap').innerHTML = Object.entries(myObject)
        .map(e => e[1].eventJson.replace("<div>", `<div class='popup-wrap hidden' id='${e[0]}'>`))
        .join('');
    
    // set up the rotate function
    const rotateItem = () => {
      let currentIndex = -1,
        p = document.querySelectorAll('.popup-wrap')
      p.forEach((e, i) => {
        if (!e.classList.contains('hidden')) {
          currentIndex = i + 1;
          e.classList.add('hidden')
        }
      });
      currentIndex = Math.max(currentIndex, 0);
      if (currentIndex >= p.length) currentIndex = 0;
      p[currentIndex].classList.remove('hidden')
    }
    const interv = setInterval(rotateItem, 1000)
    .popup-wrap {
      padding: 15px;
      background: #f0f0f0;
    }
    
    .popup-wrap.hidden {
      display: none;
    }
    <div id="popup-wrap"></div>