How to redirect URL in Javascript or jQuery
How to redirect URL in Javascript or jQuery
I will present some ways to redirect the user to another page from the client side using only plain javascript.
1) Using window.location.href you obtain a similar behavior as an HTTP redirect
1 2 3 |
<script language=”JavaScript”> window.location.href = 'http://www.google.com'; </script> |
2) Using window.location.replace
1 2 3 |
<script language=”javascript” type=”text/javascript”> window.location.replace("http://anothersite.com"); </script> |
window.location.href VS window.location.replace
It is better than using window.location.href
, because replace()
does not put the originating page in the session history, meaning the user won’t get stuck in a never-ending back-button process.
3) Using the widow.history.back you can redirect the user to the previous page he was before.
1 2 3 |
<script language=”javascript”> window.history.back(-1); </script> |
4) Using window.navigate
1 2 3 |
<script language=”javascript”> window.navigate(”page2.html”); </script> |
5) Using self.location
1 2 3 |
<script language=”JavaScript”> self.location=”page2.html”; </script> |
6) Using jQuery
1 2 3 4 |
<script language=”JavaScript”> var url = "http://google.com"; $(location).attr('href',url); </script> |
See you again in our next tutorial.