//aside is your sidebar selector
var aside = document.querySelector('aside');
//sticky sidebar on scrolling
var startScroll = aside.offsetTop;
var endScroll = window.innerHeight - aside.offsetHeight;
var currPos = window.scrollY;
document.addEventListener('scroll', () => {
var asideTop = parseInt(aside.style.top.replace('px;', ''));
if (window.scrollY < currPos) {
//scroll up
if (asideTop < startScroll) {
aside.style.top = (asideTop + currPos - window.scrollY) + 'px';
} else if (asideTop > startScroll && asideTop != startScroll) {
aside.style.top = startScroll + 'px';
}
} else {
//scroll down
if (asideTop > endScroll) {
aside.style.top = (asideTop + currPos - window.scrollY) + 'px';
} else if (asideTop < (endScroll) && asideTop != endScroll) {
aside.style.top = endScroll + 'px';
}
}
currPos = window.scrollY;
});
//this code will bring to you sidebar on refresh page
function asideToMe() {
setTimeout(() => {
aside.style.top = startScroll + 'px';
}, 300);
}
asideToMe();
body{
padding: 0 20px;
}
#content {
height: 1200px;
}
header {
width: 100%;
height: 150px;
background: #aaa;
}
main {
float: left;
width: 65%;
height: 100%;
background: linear-gradient(180deg, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
aside {
float: right;
width: 30%;
height: 800px;
position: sticky;
top: 100px;
background: linear-gradient(0deg, rgba(2,0,36,1) 0%, rgba(22,153,66,1) 51%, rgba(167,255,0,1) 100%);
}
footer {
width: 100%;
height: 70px;
background: #555;
}
<body>
<header>Header</header>
<div id="content">
<main>Content</main>
<aside>Sidebar</aside>
</div>
<footer>Footer</footer>
</body>