6

My application is an iframe app so when the user changes page they do not automatically get taken to the top. To combat this on page load I call

window.location.hash = 'tophash'

I have found however on some rare cases I need to take the user to a specific part of the page. So I make a url with #anotherID on the end. Problem is currently they are taken to tophash on page load.

What I need is if there is a hash within the url it does not run window.location.hash = 'tophash'

So my question is... how do I detech the presence of a # in the url?

1 Answer 1

3

Querying the hash property before setting it should do the job.

if ((!window.location.hash) || (window.location.hash == "#"))
 window.location.hash = "tophash";
7
  • 1
    It's not == null when it's empty, at least not on Chrome (jsbin.com/ecela4). It should be an empty string (and is on Chrome: jsbin.com/ecela4/2), but I'd probably code defensively and go with == "". Commented Sep 12, 2010 at 15:03
  • @T.J. good point! Changed to a length check and added a check for a lone # just to make sure - Chrome takes away lone #es but I wouldn't trust everyone does
    – Pekka
    Commented Sep 12, 2010 at 15:05
  • @Starlin argh, my update was humbug, sorry. Please use the one posted now
    – Pekka
    Commented Sep 12, 2010 at 15:10
  • 2
    !window.location.hash is a better way of checking hash, notice the ! Empty string, array, 0, undefined and null will all evaluate to false when using !
    – BGerrissen
    Commented Sep 12, 2010 at 15:12
  • @BGerrissen fair point! Wasn't aware ! was this flexible in JS. Changed.
    – Pekka
    Commented Sep 12, 2010 at 15:16

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.