pr -
pr -

Reputation: 358

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

Upvotes: 0

Views: 47

Answers (1)

apple apple
apple apple

Reputation: 10604

you need to

  • open(divs[(i + 1) % 6]) so it loop correctly
  • hide all divs at initial (except one)

there still some minor issue with the initial state (need to add opacity and transform, I leave it for simplicity), I think you should use proper class instead of inline css to make it easier.

for (let i = 0; i <= 5; i++) {
  let div = document.body.insertAdjacentHTML('beforeend', 
         `<div class="div" style="display:${i==0?'block':'none'}">${i}</div>`
      )
}

let divs = document.getElementsByClassName('div');
for (let i = 0; i <= 5; i++) {
  divs[i].style.backgroundColor = randomColor();
  divs[i].onclick = () => {
    close(divs[i])
    open(divs[(i + 1) % 6])
  }
}

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

Upvotes: 2

Related Questions