Skip to content

Instantly share code, notes, and snippets.

@b4dnewz
Last active January 24, 2019 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b4dnewz/5b2b2e31d2ea873d577fad31a89d3938 to your computer and use it in GitHub Desktop.
Save b4dnewz/5b2b2e31d2ea873d577fad31a89d3938 to your computer and use it in GitHub Desktop.
A VueJs custom directive to stick an element where it is keeping it into view
/**
* Directive to stick an element where it is
* when the scroll should pass him instead
*
* Just copy and paste this code inside your app
* main script before Vue is initialized and you
* have access to the directive as v-scroll-fixed
*
* @version 0.1.0
* @author Filippo b4dnewz Conti
*
*/
Vue.directive('scroll-fixed', (() => {
let fn = null
return {
inserted(el, {value = {}}) {
const offset = value.offset || 0
const {offsetWidth} = el
const {top} = el.getBoundingClientRect()
fn = function() {
if (window.scrollY >= top - offset) {
el.style.position = 'fixed'
el.style.top = `${offset}px`
el.style.width = `${offsetWidth}px`
} else {
el.style.position = 'initial'
el.style.top = 'initial'
el.style.width = 'initial'
}
}
window.addEventListener('scroll', fn)
},
unbind() {
window.removeEventListener('scroll', fn)
}
}
})())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment