Question

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.

Was it helpful?

Solution

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);
});

OTHER TIPS

You can try,

$(window).scrollTop($("#someId").offset().top - 20);

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

$(window).scrollTop($("[name="+hashtag+"]").offset().top - 20);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top