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";
Sign up to request clarification or add additional context in comments.

7 Comments

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 == "".
@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
@Starlin argh, my update was humbug, sorry. Please use the one posted now
!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 fair point! Wasn't aware ! was this flexible in JS. Changed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.