I am trying to develop a web browser user script which will scroll down my viewpoint all the way down to a certain element in a very long webpage, each time I load that webpage.
// ==UserScript==
// @name Scroll Down to Element
// @match example.com/my-webpage
// ==/UserScript==
document.querySelector('#edit-actions').scrollIntoView();
This works from console but not from the user script manager; if I run it from the console then the web browser will scroll down to the element but if I load the webpage no such scroll down will occur.
Using only the user script manager, I have also tried to wrap the code in a load event handler to try to load the code after everything else was loaded (HTML, CSS, JavaScript).
// ==UserScript==
// @name Scroll Down to Element
// @match example.com/my-webpage
// ==/UserScript==
window.addEventListener('load', () => {
document.querySelector('#edit-actions').scrollIntoView();
});
This didnât work too; after loading the webpage, no such scroll down will occur.
How to scroll down to an element just after loading the webpage that contains it?
Hi @bendqh1, the element in question might not be the from the start but get created programmatically with JS, in which case a load event listener wonât (neccessarily) help. You can have a look at the page source to check.
PS: Another possibility would be that your user script is getting executed only after the load event already got fired. Does
I have checked the webpageâs HTML source and indeed the CSS ID #edit-actions isnât there so it getâs created automatically, but shouldnât load event cover that as well (cover all non-timed-out script assets as well)?
I do want my script to be executed after the load event is fired.
Okay then this is not the issue, the element is indeed getting created asynchronously. This might also be inside another load event listener, which is just getting added after yours; in this case, waiting one tick might be enough:
Thatâs the first time I find a setTimeout without declaring the time, like 1 for one millisecond, which is the best minimum at least cognitivally for myself
Yeah it just schedules the function execution to the end of the current task queue⌠so here âaâ would get logged after âbâ, but without further delay:
I never navigated to a part of a webpage by a CSS ID.
Some web browsers may allow it but anyway an automation script would indeed require selection with something like document.querySelector().
My original post deals with selection of an element by CSS ID with JavaScript, not by manually navigating to that element from a URL bar with a CSS ID, if thatâs what you meant.
for the record, itâs not⌠a âCSSâ ID. Itâs an HTML attribute. CSS uses a selector FOR that ID, which mimics the browserâs hash usage (now. It used to require anchor tags and⌠thats a history lesson for another day). CSS has selectors for many things. Javascript uses the ID too. Doesnt make it a Javascript ID either