Javascript preventDefault
Created By: chatGPT
preventDefault
is a method that belongs to the Event
interface in JavaScript. It is used within event handlers to prevent the default action that belongs to the event from occurring. For example, if you have a form submission, calling preventDefault()
will stop the form from submitting to the server. This is particularly useful when you want to validate input data before allowing it to be processed.document.querySelector('form').addEventListener('submit', function(event) {
event.preventDefault();
// Perform validation or other actions
console.log('Form submission prevented!');
});
In the example above, when the form is attempted to be submitted, the event listener will trigger, and
preventDefault()
will halt the submission process. This allows you to handle any validation or data processing before deciding whether to proceed.function validateForm() {
// Perform validation logic
const inputElement = document.querySelector('input');
if (inputElement.value === '') {
alert('Input cannot be empty!');
return false;
}
return true;
}
document.querySelector('form').addEventListener('submit', function(event) {
if (!validateForm()) {
event.preventDefault();
}
});
Another use case for
preventDefault()
is in handling click events on links. If you want to implement a custom action when a link is clicked and prevent the link from following its URL, you can do so using this method.document.querySelector('a').addEventListener('click', function(event) {
event.preventDefault();
// Implement custom behavior here
console.log('Link clicked, but default action prevented.');
});
In this case, when a user clicks the link, the default behavior of navigating to a new page is stopped, giving you an opportunity to run your own JavaScript code instead.
document.querySelector('a').addEventListener('click', function(event) {
event.preventDefault();
// Redirect to another page after a delay
setTimeout(() => {
window.location.href = 'https://www.example.com';
}, 2000);
});