Tutorials  Articles  Notifications  Login  Signup


Rajan Kumar

Founder at HackersFriend Updated April 6, 2020, 5:19 p.m. ⋅ 1440 views

How to redirect using javascript

To redirect using Javascript we use location.href or location.replace. We pass the url value of our destination url where we want to redirect to location.href or location.replace

location.href behaves like user clicked on link while, so it keeps the url in user's history. While location.replace removes curent url from history. So, it's not possible to navigate back by clicking browser's back button. So, ideally location.replace is recommended for rediretion using javascript.

// behaves like mouse click:
window.location.href = "https://www.hackersfriend.com";

// behaves an HTTP redirect:


Redirect on a button click

To redirect to another page on button click by use you can wrap the redirect call inside a function and call this function on button click.

<!DOCTYPE html>

<h2>Redirect to another page using Javascript</h2>
<p>When you'll click on below button you will be redirected to Hackersfriend</p>

<button onclick="RedirectFunction()">Replace document</button>

function RedirectFunction() {


You can copy and run this code on HackersFriend Tryit Edtor

HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.

Create a free account