21

We have a JavaScript function named "move" which does just "windows.location.href = any given anchor".
This function works on IE, Opera and Safari, but somehow is ignored in Firefox. Researching on Google doesn't produce a satisfactory answer why it doesn't work.
Does any JavaScript guru knows about this behavior, and what would be the best practice to jump to an anchor via JavaScript?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
julio.g
  • 3,268
  • 5
  • 28
  • 25
  • 1
    I just tried setting "window.location.href" on w3school's test page and it worked. Are you sure nothing else could be causing the problem? http://www.w3schools.com/js/tryit.asp?filename=tryjs_location – Dan Herbert Nov 08 '08 at 19:59
  • Thanks for your post. Well, I tried to simplify the scenario. The whole picture is that we call the javascript from Response.Write, in an event coming from a DevExpress grid. That would be the whole context of the problem. Trying with only window.location didn't work. – julio.g Nov 08 '08 at 20:51
  • not sure if I get this "calling it from Response.Write" bit. If you are "echo"-ing it to the output, wrapped in a – scunliffe Nov 08 '08 at 21:04
  • This is what I am doing: Response.Write("";); – julio.g Nov 08 '08 at 21:18
  • It goes in a codebehind on the FocusedRowChanged event handler of a Devexpress grid – julio.g Nov 08 '08 at 21:31
  • I tried this links and anchors example from w3schools http://www.w3schools.com/js/tryit.asp?filename=tryjs_anchor1 on FireFox 3 and did not work. – julio.g Nov 08 '08 at 22:15
  • 2
    ah, ok, thats the issue, you are trying to set a hash, not a url, thus all you are telling the browser to do is to scroll to a spot on the page either with the id="myAnchor", or – scunliffe Nov 09 '08 at 00:33
  • Refer http://stackoverflow.com/questions/2345807/window-location-does-not-work-on-chrome-browser also – LCJ Dec 20 '12 at 12:41

16 Answers16

36

Have you tried just using

window.location = 'url';

In some browsers, window.location.href is a read-only property and is not the best way to set the location (even though technically it should allow you to). If you use the location property on its own, that should redirect for you in all browsers.

Mozilla's documentation has a pretty detailed explanation of how to use the window.location object.

https://developer.mozilla.org/en/DOM/window.location

Dan Herbert
  • 99,428
  • 48
  • 189
  • 219
  • 5
    it is readonly in the sense that you can't change it, but setting a location.href is totally valid and works in all browsers (except in a cornercase scenario in IE6) – scunliffe Nov 08 '08 at 21:02
  • 1
    Setting `window.location` instead of `window.location.href` causes problems in some other browsers. (I don't rememeber exactly which at the moment, though.) – Guffa Nov 19 '10 at 15:10
  • @Guffa If that's true, it's news to me. I don't know any browsers that have a problem setting the `location` object. I'd like to know what browsers can't, if you can find out... – Dan Herbert Nov 19 '10 at 18:11
  • @Craig As scunliffe pointed out, setting `window.location.href` will work, but not in IE6. Setting `window.location` works in all browsers that I've tested so far, however. – Dan Herbert May 24 '11 at 12:29
  • +1 for the updated post ;). My comment above is now irrelevant so I'll remove it. – Craig May 24 '11 at 12:37
  • @manakor I just tested it now. It worked fine for me in Firefox 4. – Dan Herbert Jan 31 '12 at 19:16
  • @scunliffe: I'm curious, what's the corner case on IE6? (If you happen to recall off the top of your head.) [This works on IE6](http://jsbin.com/awicib/2), but as you said corner case, I'm not too surprised that example doesn't replicate it. – T.J. Crowder Jun 18 '12 at 07:20
  • Trying to recall the specifics (IE6 is mostly a horrible memory these days) but somewhat related I do recall this one: http://jvleminc.blogspot.ca/2008/03/ie6-locationhref-in-onclick-event-not.html that in turn points to this: http://webbugtrack.blogspot.ca/2007/09/bug-223-magical-http-get-requests-in.html where IE6 makes the HTTP request, adds it to your history, but doesn't actually go there and general IE bugs like not passing the referrer: http://webbugtrack.blogspot.ca/2008/11/bug-421-ie-fails-to-pass-http-referer.html – scunliffe Jun 18 '12 at 14:09
  • What is yout thought on the highest voted answer in http://stackoverflow.com/questions/2345807/window-location-does-not-work-on-chrome-browser ?? It tells we must not use window.location = 'url'; – LCJ Dec 20 '12 at 12:29
  • Solved my problem. I was using `location.replace('url');` and it worked on **Chrome** and **IE**, but not on **Firefox**. Changed to `window.location` and everything is as pretty as an avocado now :) – henrique romao Jul 21 '17 at 16:50
19

If you are trying to call this javascript code after an event that is followed by a callback then you must add another line to your function:

function JSNavSomewhere()
{
    window.location.href = myUrl;
    return false;
}

in your markup for the page, the control that calls this function on click must return this function's value

<asp:button ........ onclick="return JSNavSomewhere();" />

The false return value will cancel the callback and the redirection will now work. Why this works in IE? Well I guess they were thinking differently on the issue when they prioritized the redirection over the callback.

Hope this helps!

R1CHY_RICH
  • 68
  • 8
sprite
  • 3,724
  • 3
  • 28
  • 30
  • 1
    thanks! this issue was driving me nuts until I found this ! +1 to you for saving my hairline. –  Jun 27 '11 at 11:16
  • 1
    Thanks for this, saved me some time. IE6 always needs a special kick in the pants. – Yoshi Jul 21 '11 at 22:22
5

One observation to ensure in such a scenario

Following will work in IE, but neither in Chrome nor in Firefox (the versions I tested)

 window.location.href("http://stackoverflow.com");

Following will work all the three

window.location.href = "http://stackoverflow.com";
LCJ
  • 22,196
  • 67
  • 260
  • 418
4

Maybe it's just a typo in your post and not in your code, but it's window and not windows

vincent
  • 6,368
  • 3
  • 25
  • 23
2

You've got to add return false; after the window.location.href as mentioned above.

function thisWorks()
{
    window.location.href = "http://www.google.com";
    return false;
}

function thisDoesNotWork()
{
    window.location.href = "http://www.google.com";
}
2

I am not sure to follow you.
I just tried: going with FF3 to Lua 5.1 Reference Manual (long and with lot of anchors).
Pasting javascript:window.location.href="#2.5"; alert(window.location.href); in the address bar, I went to the right anchor and it displayed the right URL. Works also with a full URL, of course.
Alternative code: javascript:(function () { window.location.href="#2.5"; })();

Perhaps you forgot the #. Common problem, also with image maps.

PhiLho
  • 40,535
  • 6
  • 96
  • 134
  • Thanks for your post. I set the # char too. Can you try without the "alert" sentence? If I put an alert, somehow it works, if I remove it, it doesn't. – julio.g Nov 08 '08 at 20:17
  • 1
    If you remove it in the bookmarklet, you have to replace it with void(0) or put the whole stuff in a function call: the bookmarklet must not have a final value. – PhiLho Nov 10 '08 at 09:11
2

I have the same problem and I guess this is related to a click event.

I have a function that moves the browser to a specific page. I attach that function to some click events: in a button and in a image. AlsoI execute the function when the user press escape (document onkeypress event).

The results are that in all cases the function is called and executed, but only when there is a click the browser goes to the address I want.

Update I got it working! with a

setTimeout( "location.replace('whatever.html');", 0 );

I don't know why the location.replace wasn't working when the event was a keypress, but with the settimeout it works :)

Update Returning false after the event when you press escape makes the redirection works. If you return true or nothing the browser will not follow

graffic
  • 1,303
  • 2
  • 14
  • 18
1

window.location.href works fine in all versions of Firefox, as does document.location.href I think that there is something else in your code that is breaking things.

drop this in a blank page, if it works, it indicates there is something else wrong on your page.

<script>
  window.location.href = 'http://www.google.com/';
</script>
scunliffe
  • 62,582
  • 25
  • 126
  • 161
0

For reference I had the same problem.

onclick = "javascript: window.location('example.html');" didn't work under FF (latest)

I just had to rewrite to onclick = "javascript: window.location = 'example.html';" to get it working

Tom Tom
  • 3,680
  • 5
  • 35
  • 40
0

I just overcome the same problem. and the problem is not in javascript, but the href attribute on the <a> element.

my js code

function sebelum_hapus()
{
var setuju = confirm ("Anda akan menghapus data...")
if (setuju)
window.location = "index.php";
}

my previous html was

<a href="" onClick="sebelum_hapus();">Klik here</a>

and I update it to

<a href="#" onClick="sebelum_hapus();">Klik here</a>

or remove the href attribute

hope this helps.

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
0

please add full javascript script tag

<script type="text/javascript" language="javascript"></script>
0

You could also use window.location.replace to jump to an anchor without register it in the browser history:

This article illustrates how to jump to an anchor and uses href as read-only property.

function navigateNext() 
{
    if (!window.location.hash) 
    {
        window.location.replace(window.location.href + unescape("#2"))
    } 
    else 
    {
        newItem = nextItem(window.location.hash)
        if (document.getElementById(newItem)) 
        {
            window.location.replace(stripHash(window.location) + "#" + newItem)
        } 
        else 
        {
            window.location.replace(stripHash(window.location) + "#1")
        }
    }
}
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

Have you tried this?

Response.Write("<script type='text/javaScript'> window.location = '#myAnchor'; </script>";); 
Mr. Muskrat
  • 22,772
  • 3
  • 20
  • 21
0
window.location.hash = "#gallery";
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
0

window.location.assign("link to next page") should work in both (chrome and firefox) browsers.

window.location.assign("link to next page")
VikasChauhan
  • 61
  • 1
  • 3
-2

Another option:

document.location.href ="..."
serg
  • 109,619
  • 77
  • 317
  • 330