Home > Blockchain >  Conditional inside an event listener doesn't give an output
Conditional inside an event listener doesn't give an output

Time:01-26

I am trying to modify https://www.w3schools.com/howto/howto_js_active_element.asp to change the button to be unpressed initially. I removed the active class from buttons and added a conditional in the js script event listener to check if class is present or not as follows but it doesn't seem to do anything:

<html>

    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <style>
            /* Style the buttons */
            .btn {
                border: none;
                outline: none;
                padding: 10px 16px;
                background-color: #f1f1f1;
                cursor: pointer;
                font-size: 18px;
            }

            /* Style the active class, and buttons on mouse-over */
            .active,
            .btn:hover {
                background-color: #666;
                color: white;
            }
        </style>
    </head>

    <body>

        <h1>Active Button</h1>
        <p>Highlight the active/current (pressed) button.</p>

        <div id="myDIV">
            <button >1</button>
            <button >2</button> // removed active class to be added later
            <button >3</button>
        </div>

        <script>
            // Add active class to the current button (highlight it)
            var header = document.getElementById("myDIV");
            var btns = header.getElementsByClassName("btn");
// This is where most changes happen such as adding a conditional to look for if active class is present
            for (var i = 0; i < btns.length; i  ) {
                btns[i].addEventListener("click", function () {
                    var current = document.getElementsByClassName("active");
                    if (current[0].classList.contains("active")) {
                        current[0].className = current[0].className.replace(" active", "");
                        this.className  = " active";
                    } else {
                        this.className  = " active";
                    }
                });
            }
        </script>

    </body>

</html>

CodePudding user response:

The issue is that since you removed the initial active class from the elements the var current = document.getElementsByClassName("active"); will return no elements.

So when you then do current[0] it will be undefined and the subsequent code will crash.

You could change the if statement to

if (current[0] && current[0].classList.contains("active")) {
  • Related