javascript - Check URL if it has a specific anchor tag - Stack Overflow

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

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?

Share Improve this question asked Aug 12, 2014 at 12:10 Fellow StrangerFellow Stranger 34.1k37 gold badges178 silver badges250 bronze badges 4
  • 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
Add a ment  | 

5 Answers 5

Reset to default 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> ...

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

相关推荐

  • javascript - Check URL if it has a specific anchor tag - Stack Overflow

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

    7小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信