How To Stop Html Page From Refreshing

There are times when you want to prevent an HTML page from refreshing, especially when you are working on a form or any other user interaction component. This blog post will walk you through the steps needed to stop an HTML page from refreshing using JavaScript.

Using JavaScript to Prevent Page Refresh

JavaScript provides an event object that allows you to intercept certain user actions, such as submitting a form. By doing this, you can prevent the default behavior of the action (e.g., page refresh) and perform your own custom actions instead.

Preventing Form Submission Refresh

Let’s assume you have a simple form like this:

To prevent the form from causing a page refresh when submitted, you can use the following JavaScript code:

document.getElementById(“myForm”).addEventListener(“submit”, function(event) {
// Perform custom actions here, e.g., sending form data via AJAX

In this example, we first add an event listener to the form with the ID myForm. When the form is submitted, the function provided in the event listener is executed. Inside the function, we call event.preventDefault() to stop the default behavior (i.e., refreshing the page).

Using Inline JavaScript

You can also use inline JavaScript to achieve the same effect. Add an onsubmit attribute to your form, like this:

Then, define the handleSubmit function in a script tag or an external JavaScript file:

function handleSubmit(event) {
// Perform custom actions here, e.g., sending form data via AJAX
return false;

Note that in this case, we also added return false; at the end of the function to explicitly state that the default behavior should not be executed.


By using JavaScript and the event object, you can easily prevent an HTML page from refreshing when a form is submitted, allowing you to perform custom actions instead. This technique is especially useful when working with user interaction components, such as forms or buttons that may trigger page refreshes by default.