What does this JavaScript snippet mean? The (evt)
part is so confusing; evt
is not a boolean. How it works?
function checkIt(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
}
What does this JavaScript snippet mean? The (evt)
part is so confusing; evt
is not a boolean. How it works?
function checkIt(evt) {
evt = (evt) ? evt : window.event
var charCode = (evt.which) ? evt.which : evt.keyCode
}
Share
Improve this question
edited Feb 11, 2023 at 23:23
Brian Tompsett - 汤莱恩
5,89372 gold badges61 silver badges133 bronze badges
asked Sep 28, 2012 at 7:01
ameshamesh
1,3193 gold badges22 silver badges54 bronze badges
2
|
4 Answers
Reset to default 9evt = (evt) ? evt : window.event
is just the inline if
syntax. It's equivalent to this code:
if (evt) {
evt = evt;
} else {
evt = window.event;
}
If evt
is truthy, evt
will be left alone. If evt
isn't truthy, it will be replaced with window.event
.
It's for event listeners.
IE6-IE8 used a totally different event method than the W3C standard.
When an event fires, a W3C-standard browser will pass an event object in the callback:
function keyPressed (e) { /* do stuff with e */ }
In your case, it's keydown
(or something else using keyCode
).
IE didn't support this, instead it had window.event
which was updated every time an event happened.
So your function is checking to see if an object was passed into it:
evt = (evt) ? evt : window.event;
// does `evt` exist, and is it anything but '', 0, false, null, undefined, NaN
// yes: evt = itself (W3C)
// no: evt = window.event (IE6-8)
Then the code asks if evt.which
exists, to try to figure out where to get the keyCode from.
evt.keyCode
is what you should be using for modern browsers, in the case of keydown
and keyup
.
Assignment expressions like that are evaluated from right to left, so this means:
- if
evt
has a truthy value, assign this value back toevt
- if not, assign the value of
window.event
regardless of its content toevt
It means: if the evt
parameter has a value then keep the value, if it doesn't have a value then use window.event
instead.
The ?
and ':' symbols are part of the ternary if operator:
var w = x ? y : z;
so above you assign either y
or z
to w
depending on whether x
is considered to be a true or false value.
If the checkIt
function was called without passing in an evt
argument i.e. checkIt()
then inside the function the evt
variable will have the value of undefined
which is treated as false
within an if condition.
evt
is set ie notundefined
ornull
orfalse
then that expression usesevt
or else it picks up thewindow event
– Anil Kumar Commented Sep 28, 2012 at 7:04