JSFiddle - React, Tailwind, and code Playground

by Nam CuPeo

HTML

<header></header>
<aside class="natural">Sticky Sidebar</aside>
<article></article>
<article></article>
<footer></footer>

CSS

header, article, footer {margin: 10px auto;}
header, footer {width: 450px; height: 60px; background-color: #8FDB9E;}
footer {height: 200px;}
article {width: 300px; position: relative; right: -75px; height: 250px; background-color: #B9E09F;}
aside {width: 130px; right: 50%; margin-right: 95px; height: 300px; background-color: #58B885; position: absolute;}

aside.fixed {position: fixed;}

aside {font-family: Helvetica, sans-serif; font-weight: bold; color: #fff; font-size: 2.5em; letter-spacing: -3px; line-height: 0.8em;}

body {background-color: #E2E6D3;}

JavaScript

$stick = $('aside');
$foot = $('footer');
margin = 10; //khoảng cách
offtop = $stick.offset().top - margin; //vị trí sidebar cách top
offbtm = $foot.offset().top - ( margin*2 + $stick.height() ); //vị trí sidebar cách footer

$(window).scroll(function () {
	scrtop = $(window).scrollTop();
  //Trường hợp 1 : bắt đầu kéo thanh cuộn xuống dưới
  if (scrtop > offtop && $stick.hasClass('natural')) {
    $stick.removeClass('natural').addClass('fixed').css('top', margin);
  }
    //Trường hợp 2 : kéo thanh cuộn lên
  if (offtop > scrtop && $stick.hasClass('fixed')) {
    $stick.removeClass('fixed').addClass('natural').css('top', 'auto');
  }
    //Trường hợp 3 : Nếu thanh cuộn đi qua vị trị của cuối (bottom) của sidebar (lúc đấy sidebar đang bị dính) thì bỏ fixed đi
  if (scrtop > offbtm && $stick.hasClass('fixed')) {
    $stick.removeClass('fixed').addClass('bottom').css('top', offbtm+margin);
  }
    //Trường hợp 4 : 
  if (offbtm > scrtop && $stick.hasClass('bottom')) {
    $stick.removeClass('bottom').addClass('fixed').css('top', margin);
  }
});
//document.write($(window).scrollTop());