As a complete Javascript novice I'm challenged by some simple concentps.
When I'm doing my javascript I'll often see stuff like this
function name(e) {
if(e.KeyCode) {
....
}
}
What does doing this accomplish? What's the e
all about?
Seems like the function is to be called by the browser (or whatever) when firing a specific event (in this case I guess it's keyboard related; e stands for event or event data).
So once fired, the caller will pass the event structure as a parameter (copied to e). JavaScript won't define any local/global variables just for the one specific call so KeyCode won't be defined but e contains that variable.
e
here is the event. Note that the letter e
isn't important, it's just a paramater name. You could call it anything, but e
is standard and makes it obvious to other people reading your code.
example:
<input type="text" onkeyup="doSomething(event)"/>
function doSomething(e) {
alert('you pressed key:' + e.keyCode);
}
So e.keyCode
is telling you which key was pressed.
The e
is the event object passed to the function in most cases, it's checking the keyCode
property of the event object that was passed in.
For example in Firefox you can do this:
document.onclick = myFunction;
function myFunction(e) {
//e is the click event object
//e.keyCode, e.target, etc.
}
This works because by default, it passes the event to the handler as the first argument. For your example does this make it clearer?
function name(someObject) { //or event, or any name works
if(someObject.keyCode) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With