javascript - location.replace()

They have: 330 posts

Joined: Apr 2000

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's picture

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

They have: 330 posts

Joined: Apr 2000

that makes sense. Thank you

They have: 5,633 posts

Joined: Jan 1970

location.replace = "http://www.yahoo.com";
'
No need to thank me.

dk01's picture

He has: 516 posts

Joined: Mar 2002

bja888 wrote:

location.replace = "http://www.yahoo.com";
'
No need to thank me.

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>
&lt;script type="text/javascript"&gt;
function doMove() {
location.replace("index2.html");
}
&lt;/script&gt;
</head>
<body>
<a href="#" onclick="doMove();">Hey</a>
</body>
</html>
'

-dk

They have: 5,633 posts

Joined: Jan 1970

location.href = "page.html";
' That works right so i figured it would be the same.

Quote: <a href="#" onclick="doMove();">Hey</a>'

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.