javascript - location.replace()
In the past I have used location.href and window.location to redirect users through my web sites. I recently found that location.replace is the proper function because it replaces the history also.
I can't get it to work. I know it should be simple, but when I trigger the function it does nothing. No error, just nothing.
Any help is greatly appreciated.
<script type='text/javascript'>
function clicked(){
location.replace("http://www.yahoo.com");
}
</script>
...
<td onClick='clicked()' align='center'>click me</td>
...
dk01 posted this at 16:52 — 24th March 2005.
He has: 516 posts
Joined: Mar 2002
This is because location.replace only works onload. Its like using a header("Location: http://yadayada.com"); in PHP. You can't change the headers after the page has been displayed.
-dk
artsapimp posted this at 17:33 — 24th March 2005.
They have: 330 posts
Joined: Apr 2000
that makes sense. Thank you
bja888 (not verified) posted this at 18:09 — 24th March 2005.
They have: 5,633 posts
Joined: Jan 1970
location.replace = "http://www.yahoo.com";
No need to thank me.
dk01 posted this at 19:55 — 24th March 2005.
He has: 516 posts
Joined: Mar 2002
Sorry to break it to ya champ but that doesn't work. His original code is correct.
I researched the problem and I think the issue is that you are using the onclick event handler on a tag. Try this and make sure that index2.html actually exists. Otherwise the script will do nothing.
<html>
<head>
<title>Yo</title>
<script type="text/javascript">
function doMove() {
location.replace("index2.html");
}
</script>
</head>
<body>
<a href="#" onclick="doMove();">Hey</a>
</body>
</html>
-dk
bja888 (not verified) posted this at 23:55 — 24th March 2005.
They have: 5,633 posts
Joined: Jan 1970
location.href = "page.html";
This would be more efficent...
<a href="javascript:doMove();">Hey</a>
'Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.