cambo1999
cambo1999

Reputation: 1

adding extra buttons is causing code not to work

i want a button to change color when clicked. My code currently works when i only have one button but stops working when i add multiple buttons. What can i add so it can work for multiple buttons?

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="btn">Button 1</button>
    <button id="btn">Button 2</button>
    
</body>
<script> 
let index = 0;
let textIndex = 0;

const colors = ['green', 'red'];
const text = ['GREEN', 'RED']

btn.addEventListener('click', function onClick() {
    btn.style.backgroundColor = colors[index];
    btn.style.color = 'white';
    btn.textText = "yes";
    btn.innerHTML = text[textIndex];

    index = index >= colors.length - 1 ? 0 : index + 1;
    textIndex = textIndex >= text.length - 1 ? 0 : textIndex + 1;
})

</script>
</html>```

Upvotes: 0

Views: 25

Answers (1)

Jon P
Jon P

Reputation: 19787

Ids must be unique, that is your first problem. Use a class then querySelectorAll to select on that class and bind an event listener to those elements.

Finally, just use one array. I've just manipulated the text in the array but for more complex use cases you could use an array of objects.

let index = 0;

const colors = ['Green', 'Red'];


document.querySelectorAll(".btn").forEach(item => item.addEventListener('click', function onClick() {
    /*this refers to the element clicke*/
    this.style.backgroundColor = colors[index].toLowerCase();
    this.style.color = 'white';
    this.textText = "yes";
    this.innerHTML = colors[index].toUpperCase();

    index = index >= colors.length - 1 ? 0 : index + 1;    
}));
<button class="btn">Button 1</button>
<button class="btn">Button 2</button>

Upvotes: 1

Related Questions