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

184
Views
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 answers
Answer question

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 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!