Rock, Paper, Scissors - Call playRound() with the CORRECT PLAYER SELECTION


#1

Hi, I’m working through the DOM Manipulation Practice right now and have been stuck on step 3 for several hours. I appreciate any help you can offer.

Step 3: Create three buttons, one for each selection. Add an event listener to the buttons that calls your playRound function with the correct playerSelection every time a button is clicked. (you can keep the console.logs for this step)

I believe that I’d like the playerSelection variable to call the id of the button that was clicked. To what should I assign the playerSelection variable?

let buttons = document.querySelectorAll(‘button’);
buttons.forEach((button) => {
button.addEventListener(‘click’, playRound());
});

function playRound(playerSelection, computerSelection) {
playerSelection =
computerSelection = computerPlay();


#2

What you need to do is grab a reference to the button that was clicked. When an event listener function is called it passes a reference to the event object to that function. You can use that reference to get the value of the ID for the element that was clicked. It would look something like the follows:

let buttons = document.querySelectorAll(‘button’);
buttons.forEach((button) => {
button.addEventListener(‘click’, playRound); // don't use parens for playRound here. It will call the function and assign the value of that to the click event handler which will then error out because the callback requires a function and not the return value from a function (unless that is also a function)
});

function playRound(e) { // e here is just a variable to grab the event object that I mentioned above that is passed into an event listener function. It could be called anything. e or event are normally used in JS.
playerSelection = e.target.id // the e object that was passed in has a property called target that references the element that the event listener originated from. You can use that to then grab the id from it.
computerSelection = computerPlay();

Hope that helps.


#3

Thanks, Couch.

That is exactly what I needed to know. The comments are damn helpful.

Much appreciated.