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.