Last active
          January 24, 2019 14:24 
        
      - 
      
- 
        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
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | /** | |
| * 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