How to execute javascript code after full load of PHP table?

56 Views Asked by At

My page has a somewhat large table (~ 300 lines), loaded from a database in PHP. When the user roll the table with any scrollbar (horizontal/vertical), I save both positions to go exactly there after page reload.

Problem is: sometimes the vertical position won't be fully restored, as if the code tried to execute before the PHP table is fully drawn.

I've tried to attach the code in different ways:

<body onload='load()'>

window.onload = load;

window.addEventListener('load',load);

document.addEventListener('DOMContentLoaded',load);

document.addEventListener('readystatechange', event => { 
    if (event.target.readyState === 'complete') {
        load();
    }
});

But none of the above works all the time. After every reload, the page sometimes scroll back to the right position, other times it scrolls upwards, until a point (~ 1000 px, which I can see in the console) where it's able to keep position indefinitely.

The code to save the scrollbar position is:

<div id='tab' onscroll='moved(this)'>

function moved(w) {
    localStorage.setItem('db.scrLeft',w.scrollLeft);
    localStorage.setItem('db.scrTop',w.scrollTop);
    console.log(w.scrollTop);
}

And to retrieve the scrollbar position, inside load() is:

if (document.getElementById('tab')) {
    var sl = parseInt(localStorage.getItem('db.scrLeft'),10);
    var st = parseInt(localStorage.getItem('db.scrTop'),10);
    if (sl && st) {
        document.getElementById('tab').scrollLeft = sl;
        document.getElementById('tab').scrollTop = st;
        console.log(st);
    }
}

Why is none of the above options respecting the proper table load, as they should? And how do I achieve it?

1

There are 1 best solutions below

0
Rodrigo On

Solved it. The scrollbar was rolling during load, causing the moved function to be called. I added a condition (loaded) to allow its execution only after load.

var loaded = false;
function moved(w) {
    if (loaded) {
        localStorage.setItem('db.scrLeft',w.scrollLeft);
        localStorage.setItem('db.scrTop',w.scrollTop);
    }
}
function load() {
    if (document.getElementById('tab')) {
        var sl = parseInt(localStorage.getItem('db.scrLeft'),10);
        var st = parseInt(localStorage.getItem('db.scrTop'),10);
        if (sl && st) {
            document.getElementById('tab').scrollLeft = sl;
            document.getElementById('tab').scrollTop = st;
            loaded = true;
        }
    }
}