JSFiddle - React, Tailwind, and code Playground

by minhee

HTML

<p>Scroll the below:</p>

<div class="scrollview">
    <div class="header-to-be-hidden">
        A. Header to be hidden when it’s scrolled.
    </div>
    <div class="middle-element-to-stuck">
        B. Middle element to stuck when it’s scrolled.
    </div>
    <div class="item">C. Item (1)</div>
    <div class="item">C. Item (2)</div>
    <div class="item">C. Item (3)</div>
    <div class="item">C. Item (4)</div>
    <div class="item">C. Item (5)</div>
    <div class="item">C. Item (6)</div>
    <div class="item">C. Item (7)</div>
    <div class="item">C. Item (8)</div>
    <div class="item">C. Item (9)</div>
    <div class="item">C. Item (10)</div>
    <div class="item">C. Item (11)</div>
    <div class="item">C. Item (13)</div>
    <div class="item">C. Item (14)</div>
    <div class="item">C. Item (15)</div>
    <div class="item">C. Item (16)</div>
    <div class="item">C. Item (17)</div>
    <div class="item">C. Item (18)</div>
    <div class="item">C. Item (19)</div>
    <div class="item">C. Item (20)</div>
</div>

CSS

.scrollview {
    overflow: scroll;
    width: 500px;
    height: 300px;
    border: 1px solid silver;
}

.scrollview div {
    height: 30px;
    line-height: 30px;
    padding-left: 5px;
    border-bottom: 1px solid silver;
    background-color: white;
}

.header-to-be-hidden {
    color: darkblue;
}

.middle-element-to-stuck {
    color: maroon;
    font-weight: bolder;
}

.fixed .middle-element-to-stuck {
    position: absolute;
    margin-top: 1px;
    width: 495px;
}

.fixed .middle-element-to-stuck + .item {
    margin-top: 31px;
}

JavaScript

$('.scrollview').scroll(function () {
    var list = $(this),
        listTop = list.offset().top,
        middle = $('.middle-element-to-stuck'),
        middleTop = middle.offset().top,
        header = $('.header-to-be-hidden'),
        headerBottom = header.offset().top + header.height();
    if (list.hasClass('fixed')) {
        if (headerBottom >= listTop) {
            list.removeClass('fixed');
        }
    } else {
        if (middleTop <= listTop) {
            list.addClass('fixed');
            middle.css('top', listTop)
        }
    }
});