Skip to content

Instantly share code, notes, and snippets.

@marker1k
Forked from lucdkny/sticky.js
Last active October 31, 2018 10:44
Show Gist options
  • Save marker1k/5505fc1a04ef532bd2c7687d31a2637b to your computer and use it in GitHub Desktop.
Save marker1k/5505fc1a04ef532bd2c7687d31a2637b to your computer and use it in GitHub Desktop.
Sticky Sideabr With Vanilla Javascript. Unstic on end element added // and getBoundingClientRect() is used
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, end) {
this.element = element;
this.addEvents();
this.position = element.getBoundingClientRect().top + pageYOffset;;
this.onScroll();
},
aboveScroll: function() {
return this.position < window.pageYOffset;
},
underScroll: function() {
return end.getBoundingClientRect().top + pageYOffset <= window.pageYOffset + end.getBoundingClientRect().height;
},
onScroll: function(event) {
if (this.aboveScroll() == true && this.underScroll() == false) {
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 = 'absolute';
this.element.style.top = 'auto';
}
};
return Sticky;
})();
// Init Sticky
var sticky = document.querySelector('.ad');
var end = document.querySelector('.end');
if (sticky)
Sticky.init(sticky, end);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment