Last active
September 7, 2017 03:47
-
-
Save dohomi/35d4a3216f5820f44176c30c4e9e9469 to your computer and use it in GitHub Desktop.
In-Viewport component based on Vuetify v-scroll
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
<template> | |
<in-viewport v-model="visible"></in-viewport> | |
</template> | |
<script> | |
export default{ | |
data(){ | |
return{ | |
visible:false | |
} | |
} | |
watch:{ | |
visible(v){ | |
// do something on v change | |
console.log(v) | |
} | |
} | |
} | |
</script> |
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
import throttle from 'lodash.throttle' | |
export default { | |
name: 'in-viewport', | |
props: { | |
value: Boolean, | |
offset: { | |
type: Number, | |
default: 124 // might depends on the toolbar fixed... | |
} | |
}, | |
render (h) { | |
return h('div', { | |
directives: [{ | |
name: 'scroll', | |
value: { | |
callback: this.onScroll | |
} | |
}] | |
}) | |
}, | |
methods: { | |
onScroll: throttle(function () { | |
this.$emit('input', this.elementInViewport(this.$el)) | |
}, 150), | |
elementInViewport (el) { | |
// https://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport | |
let top = el.offsetTop + this.offset | |
let height = el.offsetHeight | |
while (el.offsetParent) { | |
el = el.offsetParent | |
top += el.offsetTop | |
} | |
return ( | |
top < (window.pageYOffset + window.innerHeight) && (top + height) > window.pageYOffset | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment