Search code examples
javascriptonloadjs-scrollintoview

scollIntoView() works with onload, but not if we arrive at site via link


Consider the following code:

    session_start();
    if (isset($_GET['anchor']))
    {
        $_SESSION['gotoanchor'] = $_GET['anchor'];
    } else if (!isset($_SESSION['gotoanchor']))
    {
        $_SESSION['gotoanchor'] = '';
    }

    echo '<script type="text/javascript">';
    echo "window.addEventListener('load', function () {
    let jumpsegmentname = 'anchor" . $_SESSION['gotoanchor'] . "';
    let jumpsegment = document.getElementById('anchor" . $_SESSION['gotoanchor'] . "');
        if (jumpsegment != null) {
            console.log('GO TO:' + jumpsegmentname); 
            document.getElementById(jumpsegmentname).scrollIntoView();  
        }
    })";
    echo '</script>';

And the following URL:

http://localhost/translateb.php?anchor=36

I am neatly transported if I arrive at this URL from another URL on the same server, or if I refresh said URL by pressing F5.

However, when I arrive at this URL from a link in an e-mail, the page does not scroll. The page is displayed, and I have to press F5 to actually arrive at the anchor.

When the page does not scroll, the console log (GO TO x) is displayed, where x has the correct number. Only scrollIntoView does nothing.

This is in Chrome. How come?


Solution

  • You can't use only number into id, i test with ?anchor=test like:

    Correct code:

    <?php
    session_start();
    $_SESSION['gotoanchor'] = (isset($_GET['anchor'])) ? $_GET['anchor'] : '';
    ?>
    
    <div id='test'>ops</div>
    <script type="text/javascript">
        window.addEventListener('DOMContentLoaded', function () {
            let jumpsegment = document.getElementById('<?php echo $_SESSION['gotoanchor']; ?>');
            if (jumpsegment) {
                jumpsegment.scrollIntoView();
            }
        });
    </script>