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;
}
}
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>