Skip to content

Instantly share code, notes, and snippets.

@javierarques
Last active December 6, 2023 18:02
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save javierarques/36d3cd821c5a36acd352c11f88bbf2f4 to your computer and use it in GitHub Desktop.
Save javierarques/36d3cd821c5a36acd352c11f88bbf2f4 to your computer and use it in GitHub Desktop.
Sticky Sideabr With Vanilla Javascript. Detects scroll and set fixed the element. Live example: http://codepen.io/javiarques/pen/vKdgjR
// Sticky Nav Component
var Sticky = (function() {
'use strict';
var CSS_CLASS_ACTIVE = 'is-fixed';
var Sticky = {
element: null,
position: 0,
addEvents: function() {
window.addEventListener('scroll', this.onScroll.bind(this));
},
init: function(element) {
this.element = element;
this.addEvents();
this.position = element.offsetTop ;
this.onScroll();
},
aboveScroll: function() {
return this.position < window.scrollY;
},
onScroll: function(event) {
if (this.aboveScroll()) {
this.setFixed();
} else {
this.setStatic();
}
},
setFixed: function() {
this.element.classList.add(CSS_CLASS_ACTIVE);
// not needed if added with CSS Class
this.element.style.position = 'fixed';
this.element.style.top = 0;
},
setStatic: function() {
this.element.classList.remove(CSS_CLASS_ACTIVE);
// not needed if added with CSS Class
this.element.style.position = 'static';
this.element.style.top = 'auto';
}
};
return Sticky;
})();
// Init Sticky
var sticky = document.querySelector('.sticky');
if (sticky)
Sticky.init(sticky);
@daviedR
Copy link

daviedR commented Nov 6, 2019

Good scripts! Very lean.
Does this support sidebar that is longer (higher) than the viewport?

@JuanDMeGon
Copy link

For anyone getting here yet. Probably there is a better pure CSS solution.
Just use position: sticky on your CSS element: https://developer.mozilla.org/es/docs/Web/CSS/position#sticky

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment