Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend Updated April 6, 2020, 5:19 p.m. ⋅ 1585 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:
window.location.replace("http://www.hackersfriend.com");

 

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>
<html>
<body>

<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>

<script>
function RedirectFunction() {
  location.replace("https://www.hackersfriend.com");
}
</script>

</body>
</html> 

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