3

Let's say you have the following URL, (www.domain.com/page.php#_number).

I want to extract the id from the url**(_1)** and scroll to it on page load.

Your help will be appreciated.

Thanks for your help all.

The answer:-

$(document).ready(function() { 
    var $root = $('html, body');
    var ancloc = window.location.hash;
    event.preventDefault();
        $root.animate({
            scrollTop: $(ancloc).offset().top
        }, 500, function () {
            window.location.hash = href;
        });
        return false;
});
user1852196
  • 127
  • 2
  • 2
  • 10

2 Answers2

2

Why not just use an anchor <a href="http://www.domain.com/page.php#number"> and animate that. Check this link: Smooth scrolling when clicking an anchor link

Community
  • 1
  • 1
Casey Dwayne
  • 2,142
  • 1
  • 17
  • 32
  • The link you provided only triggers on click event. I want to extract the id and scroll to it on page load. – user1852196 Mar 23 '13 at 12:44
  • You can change it to whatever event you want. I personally use `$(document).ready(function(e) {}` for load events. Just remove the `.click` – Casey Dwayne Mar 23 '13 at 12:46
1

1- You can get the string "#number" by location.hash.

2-You can use a jQuery plug-in like jQuery Scrollbar Slider

You don't need to create click event, it handles that.

EDIT:

If you want it to work without click, on page load, you must prevent default browser behavior. Because browser will scroll automatically.

here is another DEMO that works on page load DEMO

Okan Kocyigit
  • 13,203
  • 18
  • 70
  • 129