Reputation: 288080
When I don't want to execute the default action that is associated with the event, I use
function listener(e){
if(e.preventDefault) e.preventDefault();
/* Other code */
}
But I have just learnt that events have the boolean cancelable
. Then, should I use this code instead?
function listener(e){
if(e.cancelable) e.preventDefault();
/* Other code */
}
I wonder:
event.preventDefault
is true
, does it really mean that the event is cancelable? Maybe if it isn't cancelable, that attribute is defined (and true
), but it isn't a function; or it's a function but if I call it it throws an error.event.cancelable
? Is there a browser which has the method event.preventDefault
but doesn't have event.cancelable
; or has the method event.cancelable
but doesn't have event.preventDefault
; or that event.cancelable
doesn't always imply that event.preventDefault
is defined and it's a function and it doesn't throw errors?Upvotes: 1
Views: 3060
Reputation: 1860
First you can check if the event is cancelable. Know that not all events are cancelable, for example the change
event.
After that you check if the event has been defaultPrevented.
if (!event.cancelable || !event.defaultPrevented) {
// execute the event logic, because the previous event didn't prevented it
}
The cancelable
check is optional, but I use it to remind myself that not all events are cancelable.
Upvotes: 0
Reputation: 413720
This:
if (e.preventDefault)
merely means that the event object has a property called "preventDefault". It's a browser feature test, because old versions of IE didn't have that. Instead, in IE you set the property "returnValue" on the event object to false
.
Thus, the reason you test for "preventDefault" is to see whether that function is available; if the property is null, you obviously can't make the function call. So when you want to prevent the default action, your code should look like this:
if (e.preventDefault)
e.preventDefault();
else
e.returnValue = false;
If the "cancelable" flag is false, then that means you cannot prevent default behavior. The "preventDefault" function is still there (if it normally would be), but calls to it are ignored for non-cancelable events. There's no need to check the flag at all, really; it's a static characteristic of the particular type of event, usually.
Upvotes: 4