Why If Statement With E.preventdefault ? - Drag And Drop Javascript
Solution 1:
The first call isn't actually calling the function, but simply checking to see if it is defined. The code is basically asking "is the e.preventDefault()
method defined?" and then executing it if it is:
// Is preventDefault() currently defined?
if (e.preventDefault) {
// Then do it.
e.preventDefault();
}
Possible Reasoning
The likely reason that this exists is that support for event.preventDefault()
wasn't added in Internet Explorer until IE9, so code similar to the following may have been more common during those dark, pre-IE9 days :
// An example of a pre-IE9 check for preventing default events
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
Solution 2:
Usually statements like this have to do with browser compatibility. For instance some browser might not have implemented the preventDefault()
function. That being said, I don't know of any browser that has this problem.
Older versions of Internet Explorer would not pass the event object as a parameter but instead the event was in the global scope (ie window.event
). But this code does not guard against that because if e
is undefined if(e.preventDefault)
will throw an exception.
Another candidate reason is that handleDragOver
is called from more than just the eventlistener. In the sample code this is not the case but perhaps there was a need for this at some point. I would consider this to be bad practise, and eventlistener should have only one input parameter and it should always be an event.
I'm confident you can remove the if
statement.
Post a Comment for "Why If Statement With E.preventdefault ? - Drag And Drop Javascript"