Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

event.target.id only questioning first option

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading