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:
- If
event.preventDefaultistrue, does it really mean that the event is cancelable? Maybe if it isn’t cancelable, that attribute is defined (andtrue), but it isn’t a function; or it’s a function but if I call it it throws an error. - Does all browsers (IE, I’m looking at you) support
event.cancelable? Is there a browser which has the methodevent.preventDefaultbut doesn’t haveevent.cancelable; or has the methodevent.cancelablebut doesn’t haveevent.preventDefault; or thatevent.cancelabledoesn’t always imply thatevent.preventDefaultis defined and it’s a function and it doesn’t throw errors?
This:
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 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.