I have code that uses event.target.id to evaluate what button is being pressed on the screen. But only the first one works. Even when I try to switch them around and still only my first button works.
var multiplyer = 1
var carparts = 0;
document.getElementById("karpartz").innerHTML = carparts;
function onButtonClick(event) {
if (event.target.id === "car") {
carparts = carparts + multiplyer;
document.getElementById("karpartz").innerHTML = carparts;
} else if (event.target.id === "clickpower") {
console.log("test (clickpower)")
} else if (event.target.id === "idle") {
console.log("test (idle scrapping)")
}
}
const button = document.querySelector('button');
button.addEventListener('click', onButtonClick);
<button id="car">
car goes here soon
</button>
<button id="clickpower">
upgrade click power
</button>
<button id="idle">
upgrade idle scrapping
</button>
<p id="karpartz"></p>
<html>
<body>
<h1>
<script type="text/javascript">
document.getElementById("karpartz").innerHTML
</script>
</h1>
</body>
</html>
I am not sure why this is happening. I think I might be doing something wrong or surpassing the limitations of JavaScript I am not sure. Please help.
document.querySelector
will only return at most 1 element, so right now you're only adding a click event listener to the first button. You can use document.querySelectorAll
to select as many as possible. Then, once you have all of those buttons, you can loop through the array-like object to add the click event listener to all buttons.
function onButtonClick(event) {
if (event.target.id === "car") {
console.log("test (car)")
} else if (event.target.id === "clickpower") {
console.log("test (clickpower)")
} else if (event.target.id === "idle") {
console.log("test (idle scrapping)")
}
}
const buttons = document.querySelectorAll('button');
for (const button of buttons) {
button.addEventListener('click', onButtonClick);
}
<button id="car">
car goes here soon
</button>
<button id="clickpower">
upgrade click power
</button>
<button id="idle">
upgrade idle scrapping
</button>