I feel lượt thích I’m always confused by one thing when it comes to lớn handling DOM events in JavaScript.

Bạn đang xem: What is the preventdefault event method in javascript?

When should I hotline stopPropagation() on the event object?When should I call preventDefault() on the event object?Should I return false?


Suppose I want to lớn handle a click sự kiện on an element.

By default an sự kiện on a DOM element is fired on the specific element clicked (say, a button) & will be propagated lớn all its parent elements tree, unless it’s stopped.

I want to lớn make sure the sự kiện is handled in my sự kiện handler, và it will “stop” there.

You can stop the propagation by calling stopPropagation() method of an event object, usually at the end of the event handler:

const link = document.getElementById('my-link')link.addEventListener('mousedown', sự kiện => // process the sự kiện // ... Event.stopPropagation())


Calling the preventDefault() method of the event object will cancel the default handling that the browser is programmed to lớn execute.

Opening a new page on an a element click event, for example.

Or submitting a size on the submit event.

Calling preventDefault() is what you need to bởi vì to completely customize the action. Perhaps by creating a fetch request lớn load some JSON instead of opening a new page on a link click.

Other event handlers defined on this same element will execute. Unless you điện thoại tư vấn event.stopImmediatePropagation().

Returning false

This is especially confusing to former (or current) jQuery developers. In jQuery, returning false from an event handler automatically called Event.preventDefault và Event.stopPropagation for us.

Xem thêm: Ưu Nhược Điểm Của Hệ Điều Hành Ms Dos Là Gì? Lợi Ích Của Ms Dos Mà Bạn Chưa Biết

In vanilla JavaScript, return false in an event handler does nothing.

download my không tính tiền JavaScript Beginner"s Handbook!

Want khổng lồ become a better website Developer? Join the 2022 website Development Bootcamp!

không tính tiền ebooks
JavaScript Python React HTML CSS Node.js Linux C Express.js Next.js Vue.js Svelte Deno ES5 to ESNext How to lớn Start a Blog