Search code examples
javascriptfunctiononclickglobal-variablesonclicklistener

{button}.onclick to change textContent


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..


Solution

  • 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>