Home > other >  Add and remove border when clicking on a button JS
Add and remove border when clicking on a button JS

Time:03-10

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>

CodePudding user response:

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>
  • Related