Sticky sidebar test
by gtempesta
HTML
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<div class="fixed">
<div class="container">
<strong>LOGO / BRAND</strong>
</div>
</div>
<div class="container main">
<div class="row">
<div class="col-10">
<h6>Title</h6>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>
<div class="col-2">
<div id="sidebar">
<div class="recap">
<div class="inner" :style="recapStyle">
<h6>Sidebar</h6>
<ul>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
CSS
body {
background: #fff;
font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, Ubuntu;
color: black;
}
.fixed{
position: fixed;
top: 0;
z-index: 20;
width: 100%;
background: grey;
padding: 20px;
font-size: 18px;
}
.main{
margin-top: 87px;
height: 1200px;
}
.inner{
position: absolute;
-webkit-transition: top 0.4s ease-in-out;
transition: top 0.4s ease-in-out;
}
Vue
new Vue({
el: "#sidebar",
data: {
scrollY: null,
top: null,
bottom: null,
marginTop: 20,
prevScroll: 0,
recapStyle: {},
},
methods: {
updatePosition(scroll) {
// using jQuery to calculate amount
// --- comment this line to see the problem without jQuery ---
const offset = $(this.$el).offset().top;
// code without jQuery according to http://youmightnotneedjquery.com/
// (not working as expected)
// --- uncomment next two lines to see the problem without jQuery ---
// const rect = this.$el.getBoundingClientRect();
// const offset = rect.top + document.body.scrollTop;
const scrollAmount = offset - scroll;
const rectHeight = $(this.$el).find('.inner').outerHeight();
if (scrollAmount < this.top) {
let updatedTop = scroll - offset + this.top;
if ((scroll + rectHeight) < this.bottom) {
this.prevScroll = updatedTop;
} else {
updatedTop = this.prevScroll;
}
this.$set(this.recapStyle, 'top', `${updatedTop}px`);
} else {
this.$delete(this.recapStyle, 'top');
}
},
},
watch: {
scrollY(scrollUpdate) {
// call `updatePosition` on scroll
this.updatePosition(scrollUpdate);
},
},
mounted() {
// calculate header size (position: fixed) and add a fixed offset
this.top = $('.fixed').outerHeight() + this.marginTop;
this.bottom = document.querySelector('.main').offsetHeight;
// update scrollY position
window.addEventListener('scroll', () => {
this.scrollY = Math.round(window.scrollY);
});
},
})