Search code examples
javascriptflexboxscrolltop

Flex container with flex-direction column-reverse will not scroll to top


I am displaying notifications in the following div in order to show the last elements at the top of the container:

<div class="flex h-full max-h-full pt-36">
    <div id="scrollDiv" class="justify-bottom z-20 flex w-full flex-col-reverse items-center overflow-y-scroll scrollbar-thin">
        <div class="notification"></div>
        <div class="notification"></div>
        <div class="notification"></div>
        <div class="notification"></div>
    </div>
</div>

Automatically, when the container overflows, it is scrolled to the bottom. I have tried to set scrollTop using the following Javascript without any success:

function scrollNotifications() {
    var element = document.getElementById('scrollDiv')
    element.scrollTop = element.scrollHeight
}

How can I scroll the container to the top when overflowing on the y axis?


Solution

  • The problem was with the scrollTop positioning. The 0 value will scroll to the bottom because of the reverse direction property. The simple trick was to set a negative value:

    function scrollNotifications() {
        var element = document.getElementById('scrollDiv')
        element.scrollTop = -element.scrollHeight
    }