Javascript: Scroll window to an anchor tag or any element

You may want to direct the browser view to a particular part of your page, either when the page is loaded, or as part of a seperate javascript routine. Below is a simple, 1 line JavaScript code that will programatically scroll the browser window to an anchor tag, or other element with an ID attribute set.

document.getElementById('MyID').scrollIntoView(true);

1 thought on “Javascript: Scroll window to an anchor tag or any element”

  1. Many thanks Steve. I dynamically created the anchor ID in ASP then the JavaScript function scrolled to that anchor on page load…
    ASP
    ===
    ‘ get the current “scroll to” ID
    Dim scrolltoID
    scrolltoID=request(“postID”)
    If scrolltoID = “” Then
    scrolltoID=”00″
    End If
    JavaScript
    ==========
    function scrolltoPost()
    {
    document.getElementById(‘postID’).scrollIntoView(true);
    return true;
    }

Comments are closed.