Mackelito
Mackelito

Reputation: 4421

Trigger event when mousemove stops

I have a menu i 3 levels.. basically, when you hover I want to open if there has not been any mouse movement for 500ms but I'm not sure how I should approach this..

my categoryNavComponent more or less contains the nav-item component..

 <ul class="top">
    <li *ngFor="let category of categories">
      <nav-item [category]="category" (mouseenter)="openFirstLevel(category)">{{ category.title }}</nav-item>
    </li>
  </ul>

I kind of guess I should have move$ = fromEvent(document, 'mousemove'); and subscribe to that in the parent component?

Any ideas are most welcome :)

Upvotes: 0

Views: 678

Answers (3)

Mackelito
Mackelito

Reputation: 4421

This is what I ended up doing and it works fine for now :)

  @Output() openCategory = new EventEmitter<boolean>();

  mouseMove$ = new Subject<MouseEvent>();
  private ngUnsubscribe$ = new Subject<void>();

  @HostListener('mouseenter', ['$event'])
  onMouseEnter() {
    this.ngUnsubscribe$ = new Subject<void>();
    this.mouseMove$.pipe(debounceTime(50), takeUntil(this.ngUnsubscribe$)).subscribe(() => {
      this.openCategory.emit();
    });
  }

  @HostListener('mousemove', ['$event'])
  onMouseMove(e: MouseEvent) {
    this.mouseMove$.next(e);
  }

  @HostListener('mouseleave', ['$event'])
  onMouseLeave() {
    this.ngUnsubscribe$.next();
    this.ngUnsubscribe$.unsubscribe();
  }

Upvotes: 0

Saber Bjeoui
Saber Bjeoui

Reputation: 124

You can do something like this:

move$ = fromEvent(document, 'mousmove');
mouseInArea$ = new Subject()
canOpen$ = mouseInArea$.pipe(
  switchMap(() => move$.pipe(switchMap(() => timer(500))) )
);

openFirstLevel() {
  this.mouseInArea$.next() 
}

Upvotes: 1

Junaid Shad
Junaid Shad

Reputation: 71

// This handler will be executed every time the cursor
// is moved over a different list item
test.addEventListener("mouseover", function( event ) {
  // highlight the mouseover target
  return;

  // reset the color after a short delay
  setTimeout(function() {
    // open your dropdown here.
  }, 500);
}, false);

maybe you need something like this.

Upvotes: 1

Related Questions