Issue
I want to apply a class to my element when the mouse stops moving. It seems I have I can detect when the mouse moves or stops (see console) but I don't know why it's not applying the style when my mouse stops moving.
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
This is because in the setTimeout case the this
keyword is pointing to the global/window object not the Component itself.
Writing the setTimeout with an arrow function will solve the problem as it doesn't have its own value of this
and will access its value from its lexical scope.
timer = setTimeout(() => { this.mouseStopped() }, 300);
Answered By - Wasif Mehmood
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.