views:

181

answers:

5

Hi, I've got a page full of links to another page with anchors on the end (like this: index.html#anchor). On the page they point to, I have a script that is supposed to read where the anchor points to in order to display something.

On firefox it works perfectly, But I've noticed that IE seems to remove the #anchor from the end of the url, so the script can't grab the text. Is there a way around this, without any server side code?

+2  A: 

How is it getting the url?

window.location.hash should contain the contents of the hash.

wombleton
That's how I've been getting it in the script, but it seems IE removes the hash from the url once it's loaded. not sure why, or even if there is a solution. Thanks anyway!
tominated
A: 

Does window.location still contain the anchor on IE, or is it removed there also? If it's still there you could use window.location and split on the hash:

var whole = "" + window.location;  // location is object, make sure it's a String
var parts = whole.split('#');
var anchor = parts[1];
Stephen P
IE doesn't seem to keep it in the window.location. Thanks for your idea though!
tominated
window.location.href?
wombleton
that doesn't work either i'm afraid. It gives the same result as window.location
tominated
A: 

Just try like this

    var url = window.location.search.substring(1)
    var arr=url.split("#")
    str=arr[1]
Pramodh
+1  A: 

I've tested the following code in IE 6, 7, and 8, and the correct hash is shown in the alert box in all cases.

<script type="text/javascript">

    function showHash() {
        var currentUrl = "" + document.location;
        var hash = "";
        var parts = currentUrl.split("#");
        if (parts.length > 1) {
            hash = parts[1];
        }
        alert("the current hash is: " + hash);
    }

</script>

<input type="button" value="Show Hash" onclick="javascript: showHash();" />

Does that code work for you?

David Mills
A: 

dmillz's answer is close to solving a problem for me. I have a page that loads with an anchor in the url string and I want to change the CSS of an ID that uses the same name as the hash from dmillz's answer.

So the if the url is "http://website.com/#car"

I want the corresponding anchor element (ie., td id="car") on the page to be highlighted on page load. I can get dmillz code to work with the alert box, but can't seem to get it to work setting the background color of the ID to yellow on page load. Any suggestions?

I changed the line

alert("the current hash is: " + hash);

to

document.getElementById(hash).style.backgroundColor = "yellow";

I'm not a javascript guy so I am sure I am doing something incredibly dumb, but any suggestions would be appreciated.

johnboat