Javascript DOM Event preventDefault() Method

Introduction

Prevent a link from opening the URL:

View in separate window

<!DOCTYPE html>
<html>
<body>

<a id="myAnchor" href="https://java2s.com/">Go to java2s.com</a>

<script>
document.getElementById("myAnchor").addEventListener("click", function(event){
  event.preventDefault()// ww  w .  j a va  2s  .  c  om
});
</script>

</body>
</html>

The preventDefault() method cancels the event if it is cancelable.

Not all events are cancelable.

Use the cancelable property to find out if an event is cancelable.

The preventDefault() method does not prevent further propagation of an event through the DOM.

Use the stopPropagation() method to prevent further propagation of an event through the DOM.




PreviousNext

Related