Reputation: 1319
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
}
Upvotes: 3
Views: 18722
Reputation: 26696
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
.
Upvotes: 3
Reputation: 20254
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.
Upvotes: 1
Reputation: 236002
Assignment expressions like that are evaluated from right to left, so this means:
evt
has a truthy value, assign this value back to evt
window.event
regardless of its content to evt
Upvotes: 1
Reputation: 298166
evt = (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
.
Upvotes: 9