65/97

Prevent the default action of an event

1. Return false for the on<event>

ele.onclick = function(e) {
    // Do some thing
    ...

    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

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();

    // Do some thing
    ...
};

ele.addEventListener('click', function(e) {
    e.preventDefault();
    ...
});

Use cases

  1. Don't follow a link when clicking it. We often use this when creating tabs.
  2. Don't submit the form when clicking its submit button. For example, we want to validate the form first.
  3. Don't open a file or download the file when dragging and dropping a file to a given area.
  4. Show a custom context menu when right-clicking an element.

Might be useful