April 20, 2021

Software Mile.com

Latest Software News and Hacks

Div creation and styling not working as expected

I’m trying to create a number of divs and iterate through them on click.
The iteration only works on every other click.
Strangely, I’m getting no errors.
I tried moving the divs variable declaration outside of the for loop.

for (let i = 0; i <= 5; i++) {
  let div = document.body.insertAdjacentHTML('beforeend', `<div class="div">${i}</div>`)
  let divs = document.getElementsByClassName('div');
  divs[i].style.backgroundColor = randomColor();
  divs[i].onclick = () => {
    close(divs[i])
    open(divs[i + 1])
  }
}

function randomColor() {
  let e = Math.floor(Math.random() * 16777215).toString(16);
  return `#${e}`;
}

function close(t) {
  t.style.transform = 'scale(0.5)'
  t.style.opacity = '0'
  setTimeout(function() {
    t.style.display = 'none'
  }, 500)
}

function open(t) {
  t.style.display = 'block'
  setTimeout(function() {
    t.style.transform = 'scale(1)'
    t.style.opacity = '1'
  }, 5)
}
div {
  height: 100%;
  width: 100%;
  position: fixed;
  top: 0;
  bottom: 0;
  right: 0;
  transition: 0.5s;
  opacity: 0;
  transform: scale(0.5);
}


Go to Source of this post
Author Of this post: pineapplerind0215
Title Of post: Div creation and styling not working as expected
Author Link: {authorlink}