Oriol
Oriol

Reputation: 288080

Avoid executing event's default action. `event.cancelable` vs `event.preventDefault`?

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:

Upvotes: 1

Views: 3060

Answers (2)

dreamLo
dreamLo

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

Pointy
Pointy

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

Related Questions