12

I'm backend developer, new to javascript. Can anyone provide a few lines of script that will allow the page to auto-scroll to the "target" element after the page loads

<html>
<bod>

<p id="target">...</p> // auto-scroll here

</bod>
</html>

Thanks

1
  • Can you please mark a correct answer. Commented Jan 1, 2014 at 9:51

2 Answers 2

14

You can use scrollIntoView on the element in window.onload event..

In your case you would be doing:

window.onload = function() {
    var el = document.getElementById('target');
    el.scrollIntoView(true);
}

Good docs can be found here: MDN scrollIntoView

Sign up to request clarification or add additional context in comments.

Comments

4

Also change your body tag to something like

<body onload="ScrollToTarget">

Then your function can be defined in the header as

function ScrollToTarget()
{
     document.getElementById("target").scrollIntoView(true);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.