0

now i want to make a web program that when i press keyboard , i change the value of global variable to 1 , if not it is set to 0 . But somehow i cannot change with addEventlistener This is my code:

<script>
var count;
function down(e) {
    console.log("down");
    count = 1 ;
    // body...
}

function up(e) {
    console.log("up");
    count = 0;
}

window.addEventListener("keydown", down);
window.addEventListener("keyup", up);

document.getElementById('demo').innerHTML = count;
//somehow the output is always undefined instead of 1 or 0 , even though the 
//function is executed
</script>
</body>

</html>
Anh Tú Mai
  • 195
  • 3
  • 14
  • Your code looks fine. You need to initialize your variable and update the DOM on the down /up event. http://jsbin.com/ninigax/edit?html,js,console,output – Shyju Jan 04 '18 at 01:23
  • Your `innerHTML` assignment is being done before either of the event handlers run. Why would you expect `count` to be incremented? – Barmar Jan 04 '18 at 01:28
  • yeah but the global variable seem not change at all ,it is still undefined , i want to change to global variable because i want to pass this to Nodejs and use it as an input for my project – Anh Tú Mai Jan 04 '18 at 01:29
  • how to set event handlers run all the time and update information to my innerHTML Barmar – Anh Tú Mai Jan 04 '18 at 01:31

2 Answers2

0

You're already almost there. You just need to do two things:

  • Give count a default value. When the page loads, probably no keys are being held down, so 0 is a good choice.
  • Update the DOM each time the event happens. So you need to call document.getElementById('demo').innerHTML = count inside both event listeners.

Once you've done that, it should update how you want:

// Give count a default value.
var count = 0;

function down(e) {
    console.log("down");
    count = 1;
    document.getElementById('demo').innerHTML = count;
    // body...
}

function up(e) {
    console.log("up");
    count = 0;
    document.getElementById('demo').innerHTML = count;
}

window.addEventListener("keydown", down);
window.addEventListener("keyup", up);

// The html won't update automatically, so we have to manually update it each
// time the count is changed. Hence this line is duplicated in both event listeners.
document.getElementById('demo').innerHTML = count;
<div id="demo"></div>
CRice
  • 29,968
  • 4
  • 57
  • 70
0

I think you are missing to update dom when event changes. Below solution will work for you.

function down(e) {
    console.log("down");
    count = 1 ;
document.getElementById('demo').innerHTML = count;

    // body...
}

function up(e) {
    console.log("up");
    count = 0;
document.getElementById('demo').innerHTML = count;

}