Search code examples
javascripthtmlfunctionjs-scrollintoview

How to make offset for ScrollintoView function


So I have a few buttons that scroll to different places of my website and highlight it yellow for a second. They work well, but the only problem is, since my top nav is 40px tall, some of the element that it scrolls to is covered. Is there any way to offset the scrollintoview property by 45px (extra 5 for border & reasonable margin) so it doesn't get covered? thank you! This is the code for one of the buttons:

function Go_to_Q_and_A() {
    var divElement = document.getElementsByClassName('QA')[0];
    divElement.scrollIntoView();
    divElement.classList.add('highlighted');

    setTimeout(function() {
        divElement.classList.remove('highlighted');
    }, 1000);
}

Solution

  • Very simple CSS only solution, add the following property: .QA { scroll-margin-top: 45px; }
    It will do as it says - add a top margin to the page scroll so that the fixed navbar is taken into account.

    function Go_to_Q_and_A() {
        var divElement = document.getElementsByClassName('QA')[0];
        divElement.scrollIntoView();
        divElement.classList.add('highlighted');
    
        setTimeout(function() {
            divElement.classList.remove('highlighted');
        }, 1000);
    }
    .QA { scroll-margin-top: 45px; }
    .highlighted { background-color: yellow; }
    .tall { height: 1000px }
    <button onclick="Go_to_Q_and_A()">QA</button>
    <div class="tall">Lorem</div>
    <div class="QA">QA</div>
    <div class="tall">Lorem</div>