Rajan Kumar

rajan

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



arrow_upward Upvote

comment Comment

arrow_downward downvote



Go back to feed

HackersFriend Updates





View more


Events


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