Search code examples
javascripthtmlcsstraversal

Traversing through them DOM


Im having trouble trying to do the following: When I hit the button(the first time), I want it to select the first box and then change the background to grey, and as the button is being pressed, I want it to jump to the next box and change that box into grey. Help Please!


    const boxes = document.querySelector('#boxes');
    const button = document.querySelector('button');

    button.addEventListener('click', () => {
        let firstChild = boxes.firstElementChild;
        for (let i = 0; i < boxes.length; i++) {
            firstChild.nextElementSibling.style.backgroundColor = 'grey';
        }
    })
    body {
        background: rgb(78, 78, 78);
    }

    .boxes {
        height: 600px;
        width: 380px;
        background: rgb(236, 236, 236);
        border-radius: 20px;
    }

    .box {
        height: 100px;
        background: rgb(26, 149, 187);
    }
    <!doctype html>
    <html lang="en">

    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

        <!-- Bootstrap CSS -->
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <!-- My CSS -->
        <link rel="stylesheet" href="main.css">

        <title>Hello, world!</title>
    </head>

    <body>
        <div class="container boxes mt-5">
            <h1 class="text-center mb-4">App.js</h1>
            <div id='boxes' class="row justify-content-around">
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
            </div>
            <div class="row mt-4 justify-content-around">
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
                <div class="col-3 box "></div>
            </div>
            <div class="container text-center mt-4">
                <button id="button" type="button" class="btn btn-warning">Submit</button>
            </div>
        </div>
</body>
</html>


Solution

  • This is one way to do it using closures:

    const boxes = document.querySelector('#boxes');
    const button = document.querySelector('button');
    
    const createListener = () => {
      let counter = 0
      return () => {
        boxes.children[counter % 
    boxes.children.length].style.backgroundColor = 'gray'
        counter++
      }
    }
    
    button.addEventListener('click', createListener())
    

    I did not test it but it should work. If you don't understand what's going on please research on closures. It'll be very useful.