This content originally appeared on DEV Community and was authored by Dan
Introduction
Have you ever clicked a “Submit” button on a form, only to see the whole page flash and reset? By default, HTML forms and links trigger a full page reload—but with one line of JavaScript, we can stop this behavior.
In this post, you’ll learn how to use event.preventDefault() to keep your page from reloading unnecessarily.
Why Use event.preventDefault()?
- Better User Experience: No jarring page refreshes.
- Faster Interactions: Handle form data without waiting for the server.
- Control: Run your own JavaScript logic before/after submission.
Step-by-Step Example
1. HTML Setup
Create a basic form:
html
<form id="noReloadForm">
<input type="text" placeholder="Type something" required>
<button type="submit">Submit</button>
</form>
<p id="demo"></p>
2. JavaScript: Stop the Reload
Add an event listener to the form:
javascript
document.getElementById("noReloadForm").addEventListener("submit", (event) => {
event.preventDefault(); // Magic line! Stops the reload.
// Get the input value
const inputValue = event.target.querySelector("input").value;
// Display it on the page (no reload needed!)
document.getElementById("demo").textContent = `Submitted: ${inputValue}`;
console.log("Form submitted without reloading!");
});
3. Try It Out
Type something in the input.
Click “Submit”.
No page reload! The text appears below the form instantly.
When to Use This
Forms: Stop resets after submission.
Links: Prevent navigation (e.g., for a “Like” button).
Buttons: Run custom JavaScript instead of default actions.
Pitfalls to Avoid
Don’t forget server-side validation!
preventDefault() only stops the browser’s default behavior.
Always validate data on the server for security.
Test accessibility:
Ensure forms work without JavaScript (progressive enhancement).
Conclusion
With event.preventDefault(), you can:
- Stop unwanted page reloads.
- Run custom JavaScript logic.
- Improve user experience.
Next Steps:
Try adding validation or an API call after event.preventDefault().
Explore other event methods like stopPropagation().
This content originally appeared on DEV Community and was authored by Dan