Jump to Page Anchor

by @jehiah on 2004-11-08 10:27
Filed under: All, Javascript

One usefull way to expand my TOC script is to auto-jump to a location in the page when a user pulls up a url with #header_2 target in it.

This won't work by default because the anchors are inserted into the page by the table of contents script. This code should be put at the end of the createTOC function.

// now we work on auto-jumping to a specific target 
// document.location.hash has the target we want to jump to
if (document.location.hash.length >= 9) // we now it's gotta be atleast '#header_x'
{
    // get rid of the '#' before our target
    var new_pos = document.location.hash.substr(1,document.location.hash.length);
    // do nothing if the requested anchor isn't in the document
    if ( document.getElementById(new_pos) != null)
    {
        // we need to go to the bottom of the page... then focus so it's in view
        // otherwise it'll be just past the bottom of the page when we focus
        window.scrollByPages(100); // yeah yeah, it might not be far enough on REALLY long pages
        document.getElementById(new_pos).focus(); // now let the browser move us up to the right spot
        // this results in the desired location being at the top of the page [or as close as possible to it]
    }
}

Get the full TOC Code including this addition. A more detailed discussion of my original TOC script is also available.

Subscribe via RSS ı Email
© 2017 - Jehiah Czebotar