Skip to content

Instantly share code, notes, and snippets.

@yongjun21
Created September 25, 2019 04:01
Show Gist options
  • Save yongjun21/e42921de4fa707e0030d0928b7d60392 to your computer and use it in GitHub Desktop.
Save yongjun21/e42921de4fa707e0030d0928b7d60392 to your computer and use it in GitHub Desktop.
Tooltip that tracks position of a target element using mutation observer
<template>
<div class="tooltip" :style="style">
<slot></slot>
</div>
</template>
<script>
export default {
props: {
target: {
type: Element,
required: true
},
anchor: {
default: 'middle',
validator: prop => [
'topleft',
'top',
'topright',
'right',
'bottomright',
'bottom',
'bottomleft',
'left',
'middle'
].includes(prop)
}
},
data () {
return {
style: {display: 'none'}
}
},
computed: {
tx () {
return this.anchor.includes('left') ? 0
: this.anchor.includes('right') ? 1
: 0.5
},
ty () {
return this.anchor.includes('top') ? 0
: this.anchor.includes('bottom') ? 1
: 0.5
}
},
methods: {
updateStyle () {
const {tx, ty} = this
const targetRect = this.target.getBoundingClientRect()
const contextRect = this.$el.parentElement.getBoundingClientRect()
this.style = {
left: (1 - tx) * targetRect.left + tx * targetRect.right - contextRect.left + 'px',
top: (1 - ty) * targetRect.top + ty * targetRect.bottom - contextRect.top + 'px'
}
}
},
mounted () {
this.updateStyle()
const observer = new MutationObserver(this.updateStyle)
observer.observe(this.target, {attributes: true})
}
}
</script>
<style lang="scss">
.tooltip {
position: absolute;
}
</style>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment