返回

Default Behavior and How to Prevent It

前端

Browsers and HTML elements come with some default behaviors, or default events.

Default Behavior of <a> Tags

<a> tags with an href attribute automatically navigate to the specified link or anchor when clicked. By preventing the default behavior of the <a> tag, clicking the link will no longer trigger navigation.

To prevent the default behavior of the <a> tag, use the preventDefault() method on the event object. The following code snippet demonstrates how to do this:

const links = document.querySelectorAll('a');

for (let i = 0; i < links.length; i++) {
  links[i].addEventListener('click', (event) => {
    event.preventDefault();
  });
}

Preventing Scrolling to Top on Empty Links

Empty links, such as those with an href attribute set to "#", typically scroll to the top of the page when clicked. To prevent this behavior, use the preventDefault() method on the event object.

The following code snippet demonstrates how to prevent scrolling to the top of the page when clicking an empty link:

const emptyLinks = document.querySelectorAll('a[href="#"]');

for (let i = 0; i < emptyLinks.length; i++) {
  emptyLinks[i].addEventListener('click', (event) => {
    event.preventDefault();
  });
}

Disabling Form Submissions

By default, forms submit when the "Submit" button is clicked. To prevent this behavior, use the preventDefault() method on the submit event.

The following code snippet demonstrates how to disable form submissions:

const forms = document.querySelectorAll('form');

for (let i = 0; i < forms.length; i++) {
  forms[i].addEventListener('submit', (event) => {
    event.preventDefault();
  });
}

Preventing Image Drag and Drop

Images can be dragged and dropped by default. To prevent this behavior, use the preventDefault() method on the dragstart event.

The following code snippet demonstrates how to prevent images from being dragged and dropped:

const images = document.querySelectorAll('img');

for (let i = 0; i < images.length; i++) {
  images[i].addEventListener('dragstart', (event) => {
    event.preventDefault();
  });
}

Preventing Text Selection

Text can be selected by default. To prevent this behavior, use the preventDefault() method on the selectstart event.

The following code snippet demonstrates how to prevent text from being selected:

const textElements = document.querySelectorAll('p, h1, h2, h3, h4, h5, h6');

for (let i = 0; i < textElements.length; i++) {
  textElements[i].addEventListener('selectstart', (event) => {
    event.preventDefault();
  });
}

By understanding default behaviors and using the preventDefault() method, developers can gain control over how users interact with their web pages, enhancing the user experience and achieving the desired functionality.