JavaScript, isn’t it an incredible tool? I’ve found that it’s the unexpected features that often bring the most joy, like the ability to check if an event is cancelable. Yes, you read that right. As a developer, I have found this particular feature to be incredibly useful when dealing with various event-driven scenarios. In this post, I am going to share with you how to check if an event is cancelable in JavaScript, a neat trick that has saved me more times than I can count.
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 of cancelable events
- To cancel the
click
event, you can check thecancelable
property and you can dopreventDefault()
which would prevent the user from clicking on something. - To cancel the
scroll
event, you can check thecancelable
property and you can dopreventDefault()
which would prevent the user from scrolling the page. - To cancel the
beforeunload
event, you can check thecancelable
property and you can dopreventDefault()
which would prevent the user from navigating away from the page.
Code to check if an event is cancelable in JavaScript
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. It will return true
if the event is cancelable and false
if the event is not cancelable.
And there you have it! You now know how to check if an event is cancelable in JavaScript. It’s been quite a journey for me, walking you through this often overlooked but incredibly useful aspect of JavaScript. As we wrap up, remember, the key to becoming a better developer is in understanding the little subtleties like this. So, keep tinkering, keep exploring, and as always, keep coding!