preventDefault() event method

Definition and Usage

If the event is cancelable, the preventDefault() method will cancel the event, which means that the default operation of the event will not occur.

For example, it is useful in the following situations:

  • click the "submit" button to prevent the form from being submitted
  • click the link to prevent the link from following the URL

Note:Not all activities can be canceled. Please use cancelable property to determine if the event is cancelable.

Note:The preventDefault() method does not prevent the event from further propagating through the DOM. Please use stopPropagation() method to solve this.

Example

Example 1

prevent the URL from opening the link:

document.getElementById("myAnchor").addEventListener("click", function(event){
  event.preventDefault();
});

try it yourself

Example 2

prevent the default operation of the checkbox:

document.getElementById("myCheckbox").addEventListener("click", function(event){
  event.preventDefault();
});

try it yourself

grammatical

event.preventDefault()

ประกาศ

ไม่มี

รายละเอียดเทคนิค

ค่ากลับ: ไม่มีค่ากลับ
DOM รุ่น: DOM Level 2 Events

การสนับสนุนโปรแกรม

ตัวเลขในตารางแสดงว่าบราวเซอร์แรกที่สนับสนุนวิธีนี้ให้สมบูรณ์

วิธี Chrome IE Firefox Safari Opera
preventDefault() การสนับสนุน 9.0 การสนับสนุน การสนับสนุน การสนับสนุน