Issue
I have an element following my mouse around the page on mousemove. It works fine but when I scroll the page, the mouse does not follow, how do I fix it so that it follows it on scroll?
https://stackblitz.com/edit/angular-lg2p6f?file=src/app/app.component.html
HTML:
<div
class="wrapper"
(mouseenter)="enter()"
(mousemove)="move($event)"
(mouseleave)="leave()"
>
<p>Start editing to see some magic happen :)</p>
<div class="sites-circle" [ngClass]="mouseMove ? 'onMove' : 'notMove'">
hello
</div>
</div>
TS:
enter(source: string) {
this.tooltip.classList.add('show');
}
mouseStopped() {
this.mouseMove = false;
console.log("mousemove: " + this.mouseMove);
}
move(e: { pageX: number; pageY: number }) {
this.mouseMove = true;
console.log("mousemove: " + this.mouseMove);
var timer;
clearTimeout(timer);
timer = setTimeout(this.mouseStopped, 300);
const tooltipStyle = this.tooltip.style;
tooltipStyle.left = e.pageX + 'px';
tooltipStyle.top = e.pageY + 'px';
}
leave() {
this.tooltip.classList.remove('show');
}
CSS:
.sites-circle.onMove {
transform: scale(3);
}
.sites-circle.notMove {
transform: scale(1) !important;
}
Solution
According to this answer, we cannot get mouse current position on scroll we can just get how much it scrolled relative to last position.
For your problem, this can be realized as follows (here is your updated stackblitz):
- Add a
(window:scroll)listener to your<div>.
<div
class="wrapper"
(mouseenter)="enter()"
(mousemove)="move($event)"
(window:scroll)="onScroll($event)"
(mouseleave)="leave()"
>
- Hold the last position, e.g.:
lastPosition = {
x: undefined,
y: undefined,
};
...
// inside your move() function
this.lastPosition.x = e.pageX;
this.lastPosition.y = e.pageY;
- Hold the last known "move" page offset:
lastMovePageOffset = {
x: undefined,
y: undefined,
};
...
// inside your move() function
this.lastMovePageOffset.y = window.pageYOffset;
- Use the difference of the current scroll position and the last known page "move" page offset to calculate the new position:
onScroll(e: any) {
if (this.lastPosition.y !== undefined) {
let pageOffsetY = 0;
if (this.lastMovePageOffset.y !== undefined) {
pageOffsetY = window.pageYOffset - this.lastMovePageOffset.y;
}
this.tooltip.style.top = this.lastPosition.y + pageOffsetY + 'px';
}
}
This can be handled similarly with the x-Position. The solution works as soon as the cursor is moved once before scrolling (caused by the general problem described in the first sentence).
Good luck!
Answered By - Tommy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.