Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

261
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda