I have this component which has a button that scrolls a target div horizontally. The Html for the buttons look like this:

<div class="col">
  <h1 class="float-left">How they compare</h1>
  <div class="btn-group" role="group" aria-label="Basic example">
    <button class="btn btn-link btn-lg" (mousedown)="scrollLeft()" (mouseup)="mouseup()" (mouseleave)="mouseup()">
      <fa-icon [icon]="['far', 'caret-square-left']"></fa-icon>
    </button>
    <button class="btn btn-link btn-lg" (mousedown)="scrollRight()" (mouseup)="mouseup()" (mouseleave)="mouseup()">
      <fa-icon [icon]=" ['far', 'caret-square-right' ]"></fa-icon>
    </button>
  </div>
</div>

As you can see, I am using mousedown, mouseup and mouseleave to control my "animation" and the methods behind these look like this:

@ViewChild('container') productTableContainerElement: ElementRef;

scrollTimeoutHandler: any

scrollLeft(): void {
  if (!this.productTableContainerElement.nativeElement) return;
  this.scrollTimeoutHandler = setInterval(() => {
    this.productTableContainerElement.nativeElement.scrollLeft -= 100;
  }, 100);
}

scrollRight(): void {
  if (!this.productTableContainerElement.nativeElement) return;
  this.scrollTimeoutHandler = setInterval(() => {
    this.productTableContainerElement.nativeElement.scrollLeft += 100;
  }, 100);
}

mouseup(): void {
  if (this.scrollTimeoutHandler) {
    clearInterval(this.scrollTimeoutHandler);
    this.scrollTimeoutHandler = null;
  }
}

This creates a very jerky scroll and doesn't really do what I want. Really I would like it to scroll when my mouse is pressed down and to stop when I release or move away from the button.

Can someone give me some indication of how I might go about this?

0 Answers