Senior
What does preventDefault do and provide an example?
sobes.tech AI
Answer from AI
The preventDefault() method in JavaScript is used to cancel the default behavior of an event. For example, if a link has a click handler, calling event.preventDefault() will prevent the link from being followed.
Example:
const link = document.querySelector('a');
link.addEventListener('click', function(event) {
event.preventDefault(); // Cancel the link navigation
alert('Navigation canceled');
});
In this example, clicking the link will not navigate to the address, but instead will show a message. This is useful when you want to implement custom behavior instead of the default.