by Sai gowtham

How to redirect to another webpage in JavaScript

In this tutorial, we are going to learn about how to redirect a user from one page to another page in JavaScript.

Consider we have contact form whenever a user submits a form we need to redirect the user from /contact-page to /home-page or some other page. In such cases, we can use the href property or replace() method in JavaScript.

Using href

window.location.href = "https://google.com"

Just open your console and run the above code, you will be redirected from the current page to google.com.

Using replace() method

window.location.replace("https://google.com")

The difference between replace() and href is, the replace() method doesn’t save the current page in the session history, so that, we can’t use the browser back button to navigate back to the previous page.

Redirecting from one page to another page by using a button click

Example:

Html

<button class="btn" >Click</button>

JavaScript

const btn = document.querySelector('.btn')


btn.addEventListener('click',()=>{
    window.location.href = "https://yournewurl.com"
})

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course