Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add and remove border when clicking on a button JS

hello I am struggling to use JS in order to make the buttons on my HTML page add a border to the button when it is clicked and to remove the border when it is clicked again. it works for the first 2 clicks but then no longer does anything after that. please excuse my js im extremely inexperienced.

JavaScript:

<script>
    var flag = true;
    var buttons = document.getElementsByClassName("btn");

    function buttonFunction() {
    if (flag) {
    for (var i = 0; i < buttons.length; i++) {
        document.getElementsByClassName("btn")[i].addEventListener("click", function() {
        this.classList.add("buttonSelect");
        flag = false
        return
        });
    }
        } else {
        if (flag == false) {
        for (var i = 0; i < buttons.length; i++) {
            document.getElementsByClassName("btn")[i].addEventListener("click", function() {
            this.classList.add("buttonUnselect");
            flag = true
            return
        });
    }
        }
    }
    }

</script>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The real issue is you’re adding both classes and never removing them. Get rid of the if else statement and just toggle the class on click. Don’t need to wrap the loop in a function either. Just let the javascript execute the event listeners at runtime.

Also, make use of the buttons var you created instead of trying to query the DOM again for the same elements.

<script>
    var buttons = document.getElementsByClassName("btn");

    for (var i = 0; i < buttons.length; i++) {
      buttons[i].addEventListener("click", function() {
        this.classList.toggle("buttonSelect");
      })
    }
</script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading