jeudi 3 juin 2021

How to hide random div on btn click via JS method .hide

Here's the issue:

  1. Got multiple divs which can get hidden (random 90 items gets hidden out of total 100) on btn click via method .style.visibility = 'hidden'
  2. However this means all hidden divs will leave a blank space in between of the rest of visible divs
  3. Need to fix this by applying the .hide method instead of .style.visibility one to the code
  4. Too bad is I Can't figure out how to get .hide be working just fine

Here's what I got:

HTML

<html>
<body>

<button id="hide-containers" onclick="hide()">Hide random containers</button>

<div class="container">Item 1</div>
<div class="container">Item 2</div>
...
<div class="container">Item 99</div>
<div class="container">Item 100</div>
</body>
</html>

JS .style.visibility method /// working pretty fine but leaving blank spaces in between of divs

    function hide() {
    var cubes = document.getElementsByClassName('container');
    for (var i = 0; i < cubes.length; i++) {
        cubes[i].style.visibility = '';
    }
    for (var i = 0; i < 90;) {
        var y = Math.floor(Math.random() * 100);
        if (cubes[y].style.visibility == '') {
            cubes[y].style.visibility = 'hidden';
            i++;
        }
    }
} 

JS .hide method // not working tho

    function hide() {
    var cubes = document.getElementsByClassName('container');
    for (var i = 0; i < cubes.length; i++) {
        cubes[i].style.visibility = '';
    }
    for (var i = 0; i < 90;) {
        var y = Math.floor(Math.random() * 100);
        for (var cubes){.hide(this);
        }
    }
} 

Question: How to rework the JS code to run it succesfully via the method .hide and so prevent hidden divs leaving a blank space in between of remaining visible divs?

Thank you guys for giving me a hand with this.




Aucun commentaire:

Enregistrer un commentaire