Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
jquery
communitycreator

How to refresh a page using JavaScript

Shubham Singh Kshatriya

Overview

In JavaScript, we can refresh a page using the following methods:

  • location.reload()
  • history.go(0)

The location.reload() method

This method reloads the current URL, like the browser's refresh button.

Syntax

window.location.reload();
The syntax of location.reload()

Parameters

This method does not accept any parameter.

Return values

This method does not return any value.

Example

Let's see an example of the location.reload() method in the code snippet below:

const btn = document.getElementById('btn')

// attach event listener on btn
btn.addEventListener('click', () => {
    // reload the page
    window.location.reload()
})

Explanation

In the index.html file,

  • Line 6: We create a button with id="btn".

In the index.js file,

  • Line 1: We use the getElementById() method to find the element with id="btn".
  • Line 4: We attach the click event listener to the button.
  • Line 6: We refresh the page using location.reload() when the button is clicked.

2. The history.go(0) method

This method uses the History object of the browser to reload a URL, depending on the value of the specified parameter.

Syntax

history.go(number);
The syntax of history.go() method

Parameters

  • number: This specifies the position to which we want to move with respect to the current URL. A negative value will move backward in history, whereas a positive value will move forward. If no parameter is passed or if the value is 0, this method will reload the current URL.

Return values

This method does not return any value.

Example

Let's see an example of the history.go() method in the code snippet below:

const btn = document.getElementById('btn')

// attach event listener on btn
btn.addEventListener('click', () => {
    // reload the page
    history.go(0);
})

Explanation

In the index.html file,

  • Line 6: We create a button with id="btn".

In the index.js file,

  • Line 1: We use the getElementById() method to find the element with id="btn".
  • Line 4: We attach the click event listener to the button.
  • Line 6: We refresh the page using history.go() when the button is clicked.

Besides these methods, we can also refresh the page by reassigning a value to the current URL, as shown below:

// re-assigning the value of current location
window.location = window.location

// for URL with POST request
window.location = window.location.pathname

RELATED TAGS

javascript
jquery
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring