My code works, but only from the second click onwards. Why? (Rock Paper Scissors)


#1

So, I’ve spent ages experimenting with this page and just using it to teach myself about HTML/CSS and Javascript. I’m satisfied and ready to move on, but there’s one little problem I’d like to understand.

The first time you click any of the buttons, it will say “Computer chose …”, but the score doesn’t start getting counted.
(I have it set so that a “draw” doesn’t affect the score, but even if I click Rock and computer chooses Scissors, I still don’t get a point, and vice-versa.)

On subsequent clicks the game starts working how it’s supposed to. I’m sure there’s a simple reason for this but I’m not seeing it!

Can anyone help?


#2

I’m at work so I haven’t fully looked into your code, but I’d suggest looking for something in your code that has the first selection picking for the computer. Every time I reload and click on a choice, it says the computer picked that choice. It’s probably something so small or maybe a computational issue, but that’s probably where I’d start.

I’ll try to look into it some more when I get home from work. This has piqued my interested haha.


#3

I’ve got it working now. Thanks to @Javier-Machin in the chatroom who helped me find part of the problem, then I also looked at this page. https://gomakethings.com/attaching-multiple-elements-to-a-single-event-listener-in-vanilla-js/

So, I had to move the playerChoice variables from the end of my JS code, up to the top. This allowed the score to start counting from the first click. (Also had to change from scissors.addEventListener to scissorsBut.addEventListener, and same for Paper)

Then, on line 140 I changed RockBut.AddEventListener. to document.AddEventListener.
this allows the onclick event to run if I click on ANY button, not just rockBut.

Once I made these changes everything is working how it’s supposed to!