While converting legacy jquery code, I stuck at getting position of element.
My goal is display floating div
above a
tag.
Here is my template.
<a href="#none" v-for="busstop in busstops"
:id="busstop.id"
@mouseenter="onMouseEnterBusStop"
@mouseleave="onMouseLeaveBusStop"
onclick="detailsOpen(this);">
<div :class="['marker-info', markInfoBusStop.markerInfoActiveClass]"
:style="markInfoBusStop.markerInfoStyle">
<p><strong>{{markInfoBusStop.busStopNo}}</strong>{{markInfoBusStop.busStopName}}</p>
<dl>
...
</dl>
</div>
Vue code is below.
data: {
markInfoBusStop: {
busStopNo: '12345',
markerInfoActiveClass: '',
markerInfoStyle: {
left: '200px',
top: '200px'
}
},
...
},
methods: {
onMouseEnterBusStop: function(ev) {
let left = ev.clientX;
let top = ev.clientY;
this.markInfoBusStop.markerInfoActiveClass = 'active';
this.markInfoBusStop.markerInfoStyle.left = left + 'px';
this.markInfoBusStop.markerInfoStyle.top = top + 'px';
}
I'm just using current mouse pointer's position, but need element's absolute position.
My legacy jquery is using $(this).position()
as below.
$(document).on("mouseenter", "a.marker", function() {
var left = $(this).position().left;
var top = $(this).position().top;
$(".marker-info").stop().addClass("active").css({"left":left, "top": top});
});
Thanks in advance.
This is not a Vue question per se, but more a javascript question. The common way to do this now is by using the element.getBoundingClientRect() method. In your case this would be:
Create a ref on your <a>
element and pass that ref in a method like this:
<a ref = "busstop"
href="#none"
v-for="busstop in busstops"
@click = getPos(busstop)>
In your methods object create the method to handle the click:
methods: {
getPos(busstop) {
const left = this.$refs.busstop.getBoundingClientRect().left
const top = this.$refs.busstop.getBoundingClientRect().top
...
}
}
Supported by all current browsers: https://caniuse.com/#feat=getboundingclientrect
More info here:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
this.markInfoBusStop.markerInfoStyle.left = left + 'px';
Above isn't reactive.
See Doc
for example (you still need to customize to fit your needs.)
data
{
left: 200,
top: 200,
}
method
onMouseEnterBusStop: function(ev) {
this.left = ev.clientX;
this.top = ev.clientY;
}
computed
markerInfoStyle: function(){
return {
left: this.left + 'px',
top: this.top + 'px'
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With