Reputation: 65
How can I check if an event (of a specific type) has occurred? Suppose I have to work with the following code:
<html>
<head>
<title>Events</title>
<script type="text/javascript">
document.addEventListener('keydown',
function (event) {
if (event.keyCode == 13) { //ENTER key was pressed
alert("Hahaha!");
}
}, false);
document.addEventListener('click',
function () {
alert("Ahahahah!");
}, false)
</script>
</head>
<body></body>
</html>
Suppose I want the alert box with the string "You pressed ENTER after the click event!" to be displayed when ENTER is pressed and after the click event has occured.
Upvotes: 0
Views: 102
Reputation: 28511
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.
Upvotes: 2
Reputation: 3695
Using a callback function would probably be the easiest. Here is an example with more information here
function mySandwich(param1, param2, callback) {
alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
callback();
}
mySandwich('ham', 'cheese', function() {
alert('Finished eating my sandwich.');
});
Upvotes: 0