If a user requests the following address (from another page), I want to scroll down to the contact form area:
.html#contact
How would I check if the URL contains the hash #contact
?
If a user requests the following address (from another page), I want to scroll down to the contact form area:
http://www.example./index.html#contact
How would I check if the URL contains the hash #contact
?
- what did you tried so far? – Bhushan Kawadkar Commented Aug 12, 2014 at 12:12
- 1 possible duplicate of How can I check if one string contains another substring in JavaScript? – MarioDS Commented Aug 12, 2014 at 12:12
- And perhaps even more specific dupe: stackoverflow./q/280634/1313143 – MarioDS Commented Aug 12, 2014 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 Commented Aug 12, 2014 at 12:18
5 Answers
Reset to default 4Don'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> ...
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!
url.match(/#contact$/)
should return the matches as an array. Just check if it's not null.
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
you can use
var urlName = document.location.href;
var hash = urlName.split("#").length;
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742371622a4431378.html
评论列表(0条)