Need javascript to automatically scroll to html target after page load

I am a backend developer new to javascript. Can anyone provide a few lines of script that will allow the page to automatically scroll to the "target" element after the page loads.

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

thanks

+4
source share
2 answers

You can use scrollIntoView for an element in the window.onload event.

In your case, you will do:

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

Good docs can be found here: MDN scrollIntoView

+8
source

Also change the 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); } 
+2
source

Source: https://habr.com/ru/post/1339946/


All Articles