Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

260
Views
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>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!