I am trying to make the page display in the browser AFTER it has fully loaded AND jumped to the scroll offset position defined in the scrollBy function. How can that effect be achieved?
Most solutions I’ve seen on the web is to hide/show the elements on “onload”. But I cant seem to get it work when offset is used.
For example, I’ve tried a couple of things so far. In the example code given change the visibility value to visible after the scrollby function has run. But for some reason the scrollby function always seems to be run last, resulting in that the page is displayed at top and immediately jumps to the offset.
Other variations I’ve tried is using “display: block” and using a overlay div which covers the whole page, which is later removed with javascript. But the result is the same, the scrollby function always seems to be run last – regardless of the order in the “goToByScroll” function.
function goToByScroll()
{
window.scrollBy(0,300); // Jumps to specific offset
document.getElementById("page").style.visibility="visible";
}
window.onload = goToByScroll;
You need to give control back to the browser in between setting the scroll position and applying the new style. Simple edit:
Otherwise, the order in which your DOM changes will be applied by the browser is non-deterministic.
Whilst JavaScript code is being executed, the browser will not apply updates to the DOM; Imagine iterating through a large table, applying formatting to every cell, the author will usually want all those changes to appear instantaneously.
The browser only applies updates to the DOM when JavaScript is idle (waiting for another event, for example).
setTimeoutis one way to delay processing and allow the browser to apply any changes made so far.However,
setTimeoutwill create a new execution context, so you won’t be able to access variables local to the function. Ideally, you should only call zero-argument functions with setTimeout, otherwise it’s just another evilevalstatement: