Prevent the default action of an event
1. Return false
for the on<event>
ele.onclick = function(e) {
...
return false;
};
It's same if you the inline attribute:
<form>
<button type="submit" onclick="return false">Click</button>
</form>
I don't recommend this approach because
- Returning
false
just doesn't make sense
- It doesn't work with the addEventListener() method
2. Use the preventDefault()
method
This method works with inline attribute
<button type="submit" onclick="event.preventDefault()">Click</button>
and event handlers:
ele.onclick = function(e) {
e.preventDefault();
...
};
ele.addEventListener('click', function(e) {
e.preventDefault();
...
});
Use cases
- Don't follow a link when clicking it. We often use this when creating tabs.
- Don't submit the form when clicking its submit button. For example, we want to validate the form first.
- Don't open a file or download the file when dragging and dropping a file to a given area.
- Show a custom context menu when right-clicking an element.
See also