Stop Button From Refreshing Page in JavaScript

stop button from refreshing a page in javascrip

Have you every thought about how you can stop button from refreshing a page in JavaScript?. A very common challenge in JavaScript is the constant refreshing of a page when a form button is clicked. You may be asking yourself if there are some kinds of bugs in your code that is actually making the page to refresh on clicking a button.

You can search all day long for bugs, but sometimes or most time you will not even find one.

This constant refreshing of your webpage when a form button is clicked is usually cause by the default function applied to buttons when submitting a form.

To stop button from refreshing a page, you need to add a built-in function which prevent the default function applied on the button.

Below is a working code to prevent the default operation on links.

Using preventDefault() to stop page from been refreshing in JavaScript

One of the most proven way to Stop Button From Refreshing Page in JavaScript is by using preventDefaul().

let’s take an example to learn how to Stop Button From Refreshing Page in JavaScript

Supposed threes are your links in your webpage

Html

<button>default</ button >
< button>continue</ button >
< button>return</ button >

Add the following code in your JavaScript file

//here you are selecting the a tag which is used to create buttons and //assigning it to a variable “button”

 var button = document.querySelectorAll("button");

//next you add an eventlistener, in this case it is a click event, //because the page refresh only when the button is clicked, you will //also need to create a function, here the function created //is “stopRefresh”

 button.addEventListener(“click”, function (stopRefresh) {

// then you add the built-in function “preventDefault”

stopRefresh.preventDefault();
 });

However, you may wish to apply this prevent default method to only a particular button.

in that case, can add a class to the button and apply the code below

<button>default</ button >
< button class=”prevent”>continue</ button >
< button>return</ button >

//here you are selecting a particular button using a class”

 var button = document.querySelector(".prevent");

//next you add an eventlistener. which is also a click event,since the //page refresh only when the button is clicked.

You will also need to //create a function, here the function created is same as the first //one “stopRefresh”

 button.addEventListener("click", function (stopRefresh) {­­­­­­

// then you add the built-in function “preventDefault”

stopRefresh.preventDefault();¬¬¬¬¬
 });

This code has actually help to prevent the constant refreshing of a page when a particular button is clicked.

but I did like to point it out that, this is not the only way to stop a button from refreshing a page in JavaScript as there might  be other method(s)­­­­­­­.

Leave a Comment

Your email address will not be published. Required fields are marked *