-2

New to javascript. I'm trying to access a variable from within a function to trigger an ajax call. Any help greatly appreciated.

document.onkeydown = logKey;
i = 0;
function logKey(e) {
    var keys = i += 1;
};
console.log(keys);

Uncaught ReferenceError: keys is not defined

It was a scope issue as pointed out by @sanketd617. I used the following from @Arun P Jonny

$(document).ready(function () {
    var idleTime = 0;
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 60000); 

    //Zero the idle timer on keypress.
    $(this).on('keypress', function (e) {
        console.log('reset: ', e.type)
        idleTime = 0;
    });


    function timerIncrement() {
        idleTime = idleTime + 1;
        if (idleTime > 1) {
            console.log(idleTime)
        }
    }
});
user77887
  • 3
  • 2
  • That `var keys` line makes `keys` exist only inside the function. You need to move the declaration outside. Like `i = 0;` (which is missing the `var`) I'm trying to guess what the code is supposed to be doing; this maybe? https://jsfiddle.net/khrismuc/jguz9s7y/ –  Aug 12 '19 at 17:39
  • Why do you need both `keys` and `i`? You're incrementing `i`, just use that. – Barmar Aug 12 '19 at 17:52

1 Answers1

0

You cannot do that.

It's the local variable of the function which cannot be accessed outside the function. There's another kind of variable called global variable which can be accessed anywhere in the script.

To understand this, consider the following example,

// Global variable
var x = 10;

function demo() {
    // Local variable of demo
    var y = 20;

    // This is valid
    console.log(y); // 20

    // This is also valid
    console.log(x); // 10
}

// This is valid
console.log(x); // 10

// This is not valid
console.log(y); // error

For your purpose, I think you want to console.log() the value of keys variable everytime you press a key. This can be done as follows:

document.onkeydown = logKey; 
var i = 0;     

function logKey(e) { 
    var keys = i += 1;
    console.log(keys)

    // If you notice, you can just remove the varible keys
    // Because it's just the value of i after increment
    console.log(i);
}; 

You might want to learn about variable scope first. Checkout this blog.

sanketd617
  • 809
  • 5
  • 16
  • Thank you for your answer. I had read in documentation that a variable would have global scope if it is the first time it is declared. I learned a valuable lesson by this and two downvotes – user77887 Aug 12 '19 at 22:13