tags:

views:

55

answers:

1

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?

+3  A: 

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

if ((!window.location.hash) || (window.location.hash == "#"))
 window.location.hash = "tophash";
Pekka
It's not `== null` when it's empty, at least not on Chrome (http://jsbin.com/ecela4). It *should* be an empty string (and is on Chrome: http://jsbin.com/ecela4/2), but I'd probably code defensively and go with `== ""`.
T.J. Crowder
hmmm == null did not work == '' did however
Starlin
@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
@Starlin argh, my update was humbug, sorry. Please use the one posted now
Pekka
!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
@BGerrissen fair point! Wasn't aware `!` was this flexible in JS. Changed.
Pekka
@BGerrissen - That's not quite accurate. They will technically evaluate to `true` when using `!` because they are all "falsey". I imagine that's what you meant. (Except that *empty array* is not "falsey" like the rest).
patrick dw
I stand corrected, rather meant 'evaluate to boolean' and yeh, empty array doesn't evaluate to false.
BGerrissen