Categories
JavaScript Answers

How to add a button that refreshes the page on click with JavaScript?

Spread the love

Sometimes, we want to add a button that refreshes the page on click with JavaScript.

In this article, we’ll look at how to add a button that refreshes the page on click with JavaScript.

How to add a button that refreshes the page on click with JavaScript?

To add a button that refreshes the page on click with JavaScript, we add a click listener to the button.

For instance, we write

<button class="refresh-button">Refresh!</button>

to add a button.

Then we write

const refreshButton = document.querySelector(".refresh-button");

const refreshPage = () => {
  location.reload();
};

refreshButton.addEventListener("click", refreshPage);

to select the button with querySelector.

And then we call addEventListener on the button to add refreshPage as the click event listener.

In refreshPage, we call location.reload to reload the page when we click on the button.

Conclusion

To add a button that refreshes the page on click with JavaScript, we add a click listener to the button.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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