You need to record the order of occurrence. JavaScript does not by default memorize event chains in the way you are describing, simply because you can trigger them in any order you want, so it would be a useless feature of the language.
Basically, when the click event fired you need to record that it has fired. The basic implementation would be to use a boolean flag.
var clickFired = false;// by default it is false.
document.addEventListener('click', function(event) {
clickFired = true;
}, false);
document.addEventListener('keydown', function(event) {
if (clickFired) {
alert('key pressed after click');
} else {
alert('key pressed before click');
};
};
JavaScript only remembers a few very specific things about events. It knows whether or not ctrlKey, altKey, shiftKey or metaKey were pressed at the time when the event was triggered, remembers the bubble rules, the trigger execution phase, targets and a few more things you can see by typing in:
var clickFired = false;// by default it is false.
document.addEventListener('click', function(event) {
console.dir(event);//Firebug command.
clickFired = true;
}, false);
Also, beware, cross browser compatible event management is unfortunately not trivial to achieve at all. Various browsers deal with events in very different ways. A basic example would be that Internet Explorer uses attachEvent(), not addEventListener().~
If you are writing code for a production environment, I would recommend you use some form of library to make your life a whole lot easier. Otherwise you will just have to re-invent the wheel, which is awesome for learning purposes, but you may find it to be tedious and time consuming. Unless you really know your way around JavaScript, writing raw code is not suitable for something you want other people to use immediately.