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

180
Visualizações
Shortening repeated actions with different id`s

I am trying to write a script that does the same thing on button press for multiple id`s. Is there a way to shorten this down in any way?

function start(){
    var b1,b2,b3,b4 = true;
    document.getElementById('btn1').onclick=btn1;
    document.getElementById('btn2').onclick=btn2;
    document.getElementById('btn3').onclick=btn3;
    document.getElementById('btn4').onclick=btn4;
}

function btn1(b1) {
    if(b1){
    document.getElementById('btn1').style.opacity=".25";
    b1=false;
    }
}
function btn2(b2) {
    if(b2){
    document.getElementById('btn2').style.opacity=".25";
    b2=false;
    }
}
function btn3(b3) {
    if(b3){
    document.getElementById('btn3').style.opacity=".25";
    b3=false;
    }
}
function btn4(b4) {
    if(b4){
    document.getElementById('btn4').style.opacity=".25";
    b4=false;
    }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Create one function for all of the buttons and add them with a loop. You can target them with a class. Snippet below:

function start(){
    const buttons = document.querySelectorAll('.button');
    for (i = 0; i < buttons.length; i++) {
      buttons[i].onclick = buttonFunction;
    }
}
start();

function buttonFunction(e) {
    e.currentTarget.style.opacity=".25";
}
<button class="button" id="btn1">1</button>
<button class="button" id="btn2">2</button>
<button class="button" id="btn3">3</button>
<button class="button" id="btn4">4</button>

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