1

If a user requests the following address (from another page), I want to scroll down to the contact form area:

http://www.example.com/index.html#contact

How would I check if the URL contains the hash #contact?

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • what did you tried so far? – Bhushan Kawadkar Aug 12 '14 at 12:12
  • 1
    possible duplicate of [How can I check if one string contains another substring in JavaScript?](http://stackoverflow.com/questions/1789945/how-can-i-check-if-one-string-contains-another-substring-in-javascript) – MarioDS Aug 12 '14 at 12:12
  • And perhaps even more specific dupe: http://stackoverflow.com/q/280634/1313143 – MarioDS Aug 12 '14 at 12:13
  • Haha you guys above are funny. The two first answers are so beautiful. And no, there is no better question/answer on SO that covers this as succintly. – Fellow Stranger Aug 12 '14 at 12:18

5 Answers5

4

Don't. The browser does that for you. Simply have a name="contact" attribute and the browser will scroll down to that element automatically. for instance:

<h2 name="contact">The contact form is below</h2>
<form> ...
Pinoniq
  • 1,365
  • 9
  • 13
4

You can use this simple code to get the URL hash.

var hash = window.location.hash;
if(hash == "#contact") {
    // code
}

Note: this will also return the "#" tag!

MeSo2
  • 450
  • 1
  • 7
  • 18
mathf
  • 316
  • 2
  • 10
1

url.match(/#contact$/) should return the matches as an array. Just check if it's not null.

Sejka
  • 51
  • 3
  • 7
0

The hash in the URL will map to the node with the same ID value. So in your case the page will auto scroll to div with an idea of #contact

Llewellyn Collins
  • 2,243
  • 2
  • 23
  • 37
  • 2
    It's actually name. (id only works in HTML5 because browsers tend to forgive you for this mistake) – Pinoniq Aug 12 '14 at 12:48
0

you can use

var urlName = document.location.href;
var hash = urlName.split("#").length;
MeSo2
  • 450
  • 1
  • 7
  • 18
Satnam singh
  • 205
  • 2
  • 3
  • 9