Need javascript to auto-scroll to the target html element after page loads

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

Add Comment
2 Answer(s)

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

Answered on July 15, 2020.
Add Comment

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); } 
Answered on July 15, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.