0

I added EventListener via Javascript and I want to select 1 element after pressing the key. Then I want to change the opacity of this element to 1

I tried to generate random numbers from 1 - 9 and check if they are the same as the element id but it didn't work.

function animate() {

}

document.addEventListener("keydown", function() {
  animate()
});
<div class="celok">
  <div id="1" class="box">Text</div>
  <div id="b" class="box">Text </div>
  <div id="c" class="box">text</div>
  <div id="d" class="box">Text</div>
  <div id="e" class="box">Text</div>
  <div id="f" class="box">Text</div>
  <div id="g" class="box">Text</div>
  <div id="h" class="box">Text</div>
  <div id="i" class="box">Text</div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Kristian
  • 3
  • 1
  • 1
    Please see [ask], then revise to show your attempt. We're not a free code writing service. – isherwood Jan 31 '23 at 14:41
  • 1
    you have no id with 2,3,4,5,6,7,8, or 9... You can create a list with all the ID's (array) and randomly pick from the array or you give them all the same class or data-attribtue and randomize on that list – tacoshy Jan 31 '23 at 14:41
  • You don't need an ID _or_ a class. They're all children of a single element. Just select that. – isherwood Jan 31 '23 at 14:50

1 Answers1

0

You could use querySelectorAll to get all the elements which are not visible (using a class).

Then get a random index of that array and apply the visible class on it to show it in the DOM

function animate() {
    const all = document.querySelectorAll('.box:not(.visible)');
    if (all.length) {
        const rnd = Math.floor(Math.random() * all.length);
        all[rnd].classList.toggle('visible');
    }
}

document.addEventListener("keydown", function() {
  animate()
});
.visible {
    opacity:1 !important;
}

.box {
    opacity: 0;
}
<div class="celok">
  <div id="1" class="box">Text</div>
  <div id="b" class="box">Text </div>
  <div id="c" class="box">Text</div>
  <div id="d" class="box">Text</div>
  <div id="e" class="box">Text</div>
  <div id="f" class="box">Text</div>
  <div id="g" class="box">Text</div>
  <div id="h" class="box">Text</div>
  <div id="i" class="box">Text</div>
</div>
0stone0
  • 34,288
  • 4
  • 39
  • 64