Reputation: 161
Why do this to check if event is undefined...?
function onMouseMove(e) {
if (typeof e === 'undefined' || typeof e.pageX === 'undefined') {
return;
}
Upvotes: 2
Views: 570
Reputation: 31
if (typeof e === 'undefined' || typeof e.pageX === 'undefined')
its check if the even handler are underfined or not otherwise return anything else ..coz this is the ie issue.
Upvotes: 2
Reputation: 148110
If you are passing event object onMouseMove then you do not need to check. But This function could be called with passing arguments in that case e needs to be checked.
<div id="div1" onmousemove="onMouseMove(event)" > mouse move test, with event </div>
<div id="div1" onmousemove="onMouseMove()" > mouse move test, without event </div>
function onMouseMove(e) {
if (typeof e === 'undefined' || typeof e.pageX === 'undefined') {
alert("With e");
}
else
{
alert("Without e");
}
}
Upvotes: 2
Reputation: 1905
That check stems from different browsers calling the event in their own ways. Some browsers do not pass in e
and it is defined as the global event
object that you must access each time a mouseHandler is called.
For example, the following code will always give you the event object regardless of browser:
e = e || window.event
For more details, check out the article found by raina77ow
:
http://www.quirksmode.org/js/events_access.html
Upvotes: 3
Reputation: 1535
It is generally good practice to check your inputs, especially in a loosely-typed language like JavaScript. In this case we want to make sure the expected input is both defined, and if it is defined, we need to make sure it is an object with the property pageX
. Simply checking the first clause of that conditional is insufficient because it may be missing pageX
and only checking the second clause would throw an error if e
was undefined entirely.
Upvotes: 0
Reputation: 186984
The only thing I can think of to check if the function is being invoked by a real event in the browser, or being called by other JS code.
For example, this will execute when an event is fired, passing in an event object.
$('#someID').on('mousemove', onMouseMove);
However, this will not pass any arguments at all
onMouseMove();
Why you need the check in your code though is a little odd. You usually wouldn't invoke event handlers directly. So it's a little odd.
Upvotes: 0