-1

I need some javascript that will extract an anchor ('hashtag' in the case below) from the page's url and autoscroll to the tag with that name.

Here's an example url: www.somelink.com/post1/#hashtag

I tried putting the url in an anchor tag like this; <a name="hashtag" href="www.somelink.com/post1/#hashtag"> and it works fine. But I want to mimic that functionality in code.

I tried doing it in jQuery, but there I need to have an id defined.

I searched the forum but i couldn't find what I was looking for.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
x-y-z-select
  • 87
  • 2
  • 9
  • 1
    Questions asking for code must **demonstrate a minimal understanding of the problem being solved**. Include attempted solutions, why they didn't work, and the *expected* results. See also: [Stack Overflow question checklist](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist) – Danny Beckett Dec 12 '13 at 09:45
  • @DannyBeckett I think the OP IS doing that, but since it's his first post; and there's probably a language barrier too; he doesn't know to what extent he should include the detail of his problem – pythonian29033 Dec 12 '13 at 10:05

3 Answers3

0

You can try,

$(window).scrollTop($("#someId").offset().top - 20);
Ömer Faruk Aplak
  • 889
  • 2
  • 9
  • 21
0

Playing off Omer's answer, except using a name instead of the ID:

$(window).scrollTop($("[name="+hashtag+"]").offset().top - 20);
Danny Beckett
  • 20,529
  • 24
  • 107
  • 134
Dan Goodspeed
  • 3,484
  • 4
  • 26
  • 35
0

are you looking to extract the hashtag from the url first, then go to that part in the page?

like this?;

$(document).ready(function(){
   var tag = window.url.split('#');
   tag = tag[tag.length - 1];

   $('html, body').animate({
      scrollTop: $("[name='" + tag + "']").offset().top
   },10);
});
pythonian29033
  • 5,148
  • 5
  • 31
  • 56