DebugPointer
Published on

Check if event is cancelable in JavaScript

Check if event is cancelable in JavaScript

The cancelable is a read-only property of the Event interface. It indicates whether an event can be canceled or not. It returns a boolean value either true or false .

If the event is cancelable, then the value of the cancelable property will be true and the event listener can stop the event from occurring.

If the event is not cancelable, then the value of the cancelable property will be false and the event listener cannot stop the event from occurring.

In the Event listeners, you need to check cancelable property before invoking their preventDefault() methods.

Examples

  • To cancel the click event, you can check the cancelable property and you can do preventDefault() which would prevent the user from clicking on something.
  • To cancel the scroll event, you can check the cancelable property and you can do preventDefault() which would prevent the user from scrolling the page.
  • To cancel the beforeunload event, you can check the cancelable property and you can do preventDefault() which would prevent the user from navigating away from the page.

Here is a sample code to check if an event is cancelable-

<!DOCTYPE html>
<html>
<body>

<p>Click the button to see if event is cancelable</p>

<button onclick="isEventCancelable(event)">Try it</button>

<p id="demo"></p>

<script>
function isEventCancelable(event) {
  var x = event.cancelable;
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>

Here is a generic JavaScript Function which you can use to see if an event is cancelabe-

function isEventCancelable(event) {
  return event.cancelable
}

You can call this function from anywhere in the code to check if the event is cancelable.