Question

var isPressed =0;
document.body.onkeypress = function(evt)
{
  evt = evt || window.event;

    if (evt.keyCode!=='undefined') {
        // Do your stuff here
        isPressed = 1;
        console.log(isPressed);//Here it gives 1
    }
//return isPressed;
}
result = navigator.appVersion +"|"+n+"|"+getStyle(mydiv,'opacity')+"|"+history.length+"|"+metarefesh+"|"+hasFocus+"|"+navigator.platform+"|"+parent.top.document.referrer+"|"+activexenable+"|"+javaEnabled+"|"+hasFlash+"|"+navigator.plugins.length+"|"+ hasMouseMoved+"|"+isClicked +"|"+**isPressed**+"|"+isresized+"|"+isScrolled+"|"+getStyle(mydiv,'zIndex');

console.log(result); console.log(isPressed)//This gives out zero even though I have pressed a key and it has changed to 1.

If I do a console.log(isPressed) inside the if loop in question it works.Its a scoping issue I am not aware of.Please help.

Thanks in advance

Was it helpful?

Solution

The problem is one of synchronization. Your code is read as:

when a key is pressed, set isPressed to one

show the value of isPressed

The the first instruction just says what will happen at a later point in time and it is completed. The second instruction follows immediately, before any keys are pressed, so it shows 0. If you were to do a third instruction:

window.setTimeout(function(){console.log(isPressed)}, 3000);

and press a key right after the page load (before 3 seconds pass), you will see a log with isPressed set to 1.

If you have additional logic that needs to be executed after a key is pressed, you need to place it at the comment "Do your stuff here".

OTHER TIPS

Here's the core answer to why those console.logs are outputting what they are:

Javascript has this concept of events that are handled asynchronously. You leverage this when you use the onkeypress event.

The rest of the JS file does what it needs to do (including setting the event), then when the event is fired (by you pressing a key) it runs the code inside.

In practice the JS File is doing this:

  1. Set a variable isPressed to 0.
  2. Set this anonymous function to happen onkeypress.
  3. Log isPressed to the console.
  4. Whenever onkeypress actually happens, let's run that anonymous function that we set in step 2.

When you reach step 3, you haven't actually done anything to the isPressed variable, so it's logging it as 0.

Later, when you fire onkeypressed you're actually changing the value of isPressed, so it's logging as 1.


You should also be mindful that the anonymous function bound to onkeypress isn't specifically returning isPressed. You would need to add return isPressed to the bottom (where that comment is).

Since this is an anonymous function bound to an event, there isn't really a good reason to do that. The value won't go anywhere, and the scoping you have set up is ideal if you want to manipulate the isPressed variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top