3

How can I detect with javascript if an attribute "#" is appended to an url ?

I need a cross-browser solution. I'm currently using the following code, but it works only in Firefox:

if ((window.location.hash) || (window.location.hash != "#"))
    window.scrollBy(0,-60);

thanks

4
  • In which browser does it fail? According to w3schools (w3schools.com/jsref/prop_loc_hash.asp) location.hash should work in all major browsers. Commented Feb 6, 2011 at 16:15
  • @Martin Buberl So you are saying that theoretically I just need the first part of the if statement ? window.location.hash ? Commented Feb 6, 2011 at 16:17
  • I believe he's saying that your code should work in all browsers. Commented Feb 6, 2011 at 16:20
  • If you jst want to check if there is an appending hash, you could simply write: if(!!window.location.hash) Commented Feb 6, 2011 at 16:21

4 Answers 4

3

First, there seems to be an error in your posted code. If you're going for the common string is neither null nor empty nor '#' pattern, it should be:

if (window.location.hash && window.location.hash != "#")
    window.scrollBy(0,-60);

That said, since Location.hash is well-supported, the code above should work on all modern browsers.

Sign up to request clarification or add additional context in comments.

2 Comments

by the way, is window.scrollBy(0,-60); cross-browser ? The hash is no correctly detected in all browsers, but it doesn't scroll in the same way for all of them...
scrollBy() is also widely supported. The discrepancies between browsers might be because they render your page in quirks mode. What's your DOCTYPE?
1

The following line should do the job for you:

if(!!window.location.hash) // if 'true' you have an appending hash
     window.scrollBy(0,-60);

According to w3schools location.hash should work in all major browsers.

1 Comment

The first ! checks if the hash is undefined or empty. Which will return a false if there is an hash in the URL. This gets just negated with the second ! to fit the logic. You could also write if(!window.location.hash == false).
1

If you're finding that the hash property doesn't work in a key browser, you could always just do string parsing, a naive implementation might look like:

var url = window.location.href;
var hashLoc = url.lastIndexOf('#');
if(hashLoc > -1 && hashLoc < url.length )
     window.scrollBy(0,-60);

Comments

0

For good cross-browser support you can turn to jQuery. It might be overkill for your project, but overall it makes js developing much easier. There is an excellent hashchange plugin which I have used with great success for a couple of months.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.