I'm trying make simple game "Rock Paper Scissors". At this moment I got stuck in changing value of Global Variable. Situation: (for ex.) Click => [Rock]. I have to store this into Global Variable's ("playerMove").
const rock = document.createElement('button');
/*
*/
let playerMove;
playerMove = '';
I arleady try
rock.onclick = function() {
playerMove = 'Rock'; // Test in function..
}
but Its only work in function (Yea, we all know global variable doesn't work that way so..). I may be able to fix that problem soon but at this moment my mind can't think any better than this :|, I want help to find any good resource about this to (how) change textContent / Value of element by clicking on button.
Sorry for my bad English..
CodePudding user response:
You can use HTMLButtonElement.addEventListener()
to listen for "click" events, and then do whatever you want to, a simple demo
const btn = document.getElementById('test');
const container = document.getElementById('val');
btn.addEventListener('click', () => {
container.textContent = 'works'
})
<div id="val">test</div>
<button id="test">click me</button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
To update the playerMove variable you could use a function that set that value.
document.createElement('button');
const rock = document.querySelector('button');
let playerMove = ''
const updateMove = (move) => {
playerMove = move;
}
rock.onclick = () => {
updateMove('Rock');
}
CodePudding user response:
const rock = document.getElementById('button');
console.log(rock)
let playerMove;
playerMove = '';
rock.addEventListener('click',(e)=>{
playerMove =e.target.innerHTML;
console.log(playerMove);
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Aide</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<header>
<button id="button">Rock</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
strong text
This code works perfectly. it takes the text that the button contains. I think your mistake is that you didn't declare that the button you created a js is a child of body.
CodePudding user response:
Ty guys
Well, I will explain lil more about what playerMove was doing..
playerText.textContent = playerMove;
so I simple was trying to change playerMove but after I see AnanthDev answer >>
function playerMove(element, move) {
element.addEventListener('click', () => {
playerText.textContent = move;
})
}
playerMove(rock, 'Rock');
playerMove(scissors, 'Scissors');
playerMove(paper, 'Paper');