Search code examples
javascriptfunctionvarkeystroke

How can I change the var of a javascript function by pressing a key on the keyboard?


I have a piece of code here and I want to be able to press a key (f.i. the "1" key) so var isRunning = false. When I press another key (f.i. the "2" key) var isRunning should change back to isRunning = true.

It needs to be as simple as possible (javascript/html), no jquery. I just want to alter the value of this var with a definable keystroke.

This is the code:

<script type="text/javascript">
var pages=[];
pages[0]="page0.html"
pages[1]="page1.html"
pages[2]="page2.html"

var time = 33000; 
var currentIndex = 0; 
var isRunning = true;

function pageChange() { 
    if(isRunning){
        if(currentIndex == 0){ 
            pages = shuffle(pages); 
            console.log(pages);
            currentIndex = pages.length; 
        }
        currentIndex--; 
        document.getElementById("frame").src=pages[currentIndex]; 
        console.log(currentIndex);
    }
    setTimeout(function() { pageChange(); }, time);
};

window.onload = function(){
    pageChange();
}


</script>

Solution

  • This Should do the trick ;)

     document.addEventListener('keydown', function(event) {
            if(event.keyCode == 49) { //keycode 49 is '1'
                isRunning = false;
            }
            else if(event.keyCode == 50) { //keycode 50 is '2'
                isRunning = true;
            }
        });