Skip to content

Instantly share code, notes, and snippets.

@chy4egg
Last active April 19, 2018 07:30
Show Gist options
  • Save chy4egg/c5897a7db820a3e0ad9dfa180936a2d8 to your computer and use it in GitHub Desktop.
Save chy4egg/c5897a7db820a3e0ad9dfa180936a2d8 to your computer and use it in GitHub Desktop.
StickyBar (js) es6 + babel + jQuery
/**
* ENG
* Makes element fixed only for the mobile version of site (until 768px)
* @constructor
* @param {string} sTarget - target css-class for the element, which becomes fixed (.j-sticky-bar)
* @param {string} sFixedClass - the name of the css-class you want to add to the sTarget element (j-fixed)
* @param {sContent} sFixedClass - when sTarget becomes fixed, sContent element gets additional padding-top (body)
*/
/**
* RUS
* Делает элемент фиксированным (только для моб. версии сайта до 768px)
* @constructor
* @param {string} sTarget - css-класс для элемента, который становится фиксированным (.j-sticky-bar)
* @param {string} sFixedClass - css-класс, который добавится sTarget-элементу (j-fixed)
* @param {sContent} sFixedClass - когда sTarget получает sFixedClass sContent получает дополнительный отступ (body)
*/
export default class stickyBar {
constructor(sTarget = ".j-sticky-bar", sFixedClass = "j-fixed", sContent = 'body') {
this._oTarget = ($(sTarget).get(0));
this._oContent = ($(sContent).get(0));
this._iTargetTop = null;
this._iTargetHeight = null;
this._iStartPoint = null;
this._iWindowPoint = null;
this._getStartedParams = () => {
this._iTargetTop = this._oTarget.offsetTop;
this._iTargetHeight = this._oTarget.offsetHeight;
this._iStartPoint = this._iTargetTop + (this._iTargetHeight * 2);
};
this._getWindowPoint = () => {
this._iWindowPoint = window.pageYOffset;
};
this.fixedOn = () => {
$(this._oTarget).addClass(sFixedClass);
$(this._oContent).css("padding-top", this._iTargetHeight + "px" );
};
this.fixedOff = () => {
$(this._oTarget).removeClass(sFixedClass);
$(this._oContent).css("padding-top", "initial" );
};
this.checkState = () => {
if ((this._iStartPoint <= this._iWindowPoint) && (window.innerWidth < 768)) {
this.fixedOn();
} else {
this.fixedOff();
}
};
this.afterResize = () => {
if ($(this._oTarget).height() > 0) {
this._getStartedParams();
this._getWindowPoint();
this.checkState();
} else {
this.fixedOff();
}
};
$(window).on("load", ()=> {
this._getStartedParams();
});
$(window).on("scroll", ()=> {
this._getWindowPoint();
this.checkState();
});
$(window).on("resize", ()=> {
this.afterResize();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment