Check
javascript
April 22, 20202 min read

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.

Share this blog
Tagged in :
javascript
Like what you read?
Subscribe to our Newsletter
Subscribe to our email newsletter and unlock access to members-only content and exclusive updates.
About the Author
Satvik
Satvik
Entrepreneur
Satvik is a passionate developer turned Entrepreneur. He is fascinated by JavaScript, Operating System, Deep Learning, AR/VR. He has published several research papers and applied for patents in the field as well. Satvik is a speaker in conferences, meetups talking about Artificial Intelligence, JavaScript and related subjects. His goal is to solve complex problems that people face with automation. Related projects can be seen at - [Projects](/projects)
View all articles
Previous Article
Next Article