1

I want to make a website similar to http://www.lidogotlights.com but I just can't seem to figure out the code to bring up an image to your screen when a key is pressed. I was able to open up the page source of the website, and it's basically just GIFs triggered on a pressed key. I seem to be just going in circles with my searches, I'm pretty sure that i need a KeyListener, I just don't know how to start. And that I might have to preload the images or hide them?

Also, is this possible with just javascript?

*P.S. I'm still very new coding so this doesn't need to be perfect,I just want to figure out how to perform the key events function.

Iyves
  • 63
  • 5
  • the website uses react,typescript & google web analytics – brk Nov 19 '16 at 06:14
  • Possible duplicate of [jQuery Event Keypress: Which key was pressed?](http://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed) – Adam Azad Nov 19 '16 at 06:31

1 Answers1

3

One way to do it would be to add an event-listener to the window like:

window.addEventListener("keypress", checkKeyPressed, false);

function checkKeyPressed(e) {
    if (e.charCode == "97") {
        alert("The 'a' key is pressed.");
    }
}

In place of the alert you can change the background image to the required gif.

[EDIT] Also I noticed upon pressing a key without lifting causes some weird behavior. To solve that a pause can be used inside the function like:

function checkKeyPressed(e) {
        if (e.charCode == "97") {
            //Change background gif
            var currentTime = new Date().getTime();
            miliseconds = //length of gif
            while (currentTime + miliseconds >= new Date().getTime()) {
            }
            //Change background gif to default
    }
Ganesh Kathiresan
  • 2,068
  • 2
  • 22
  • 33