Founder & Programmer at HackersFriend Updated April 6, 2020, 5:19 p.m. ⋅ 633 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

Go back to feed

HackersFriend Updates

View more


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details

Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details