Tips for creating a seamless horizontal scrolling effect in Angular when hovering (automatically)

One of the components I'm working on features a gallery with an X axis orientation.

<div class="gallery">
    <div (mouseenter)="scrollTo('left', $event)" (mouseleave)="clearIntervalRepeater()" class="left"></div>
    <div (mouseenter)="scrollTo('right', $event)"  (mouseleave)="clearIntervalRepeater()" class="right"></div>
    <div class="container-fluid">
        <div #sidewayScroller class="sideway">
            <img *ngFor="let item of galleryImages" [src]="item" alt="gallery-image">
        </div>
    </div>
</div>

The "left" and "right" divs inside are transparent, absolute elements meant for hover effects on the #sidewayScroller element.

I am attempting to achieve a smooth scroll effect when hovering over the "left" or "right" side.

Hover function :

  scrollTo(position, event: HTMLElement){
    if(position == 'left'){
      console.log('left');
      this.repeater = setInterval(() => {
        this.el.nativeElement.scrollTo({
          left: this.el.nativeElement.scrollLeft - 200,
          behavior: 'smooth',
        })
      }, 150);
    } else {
      this.repeater = setInterval(() => {
        console.log('right');
      this.el.nativeElement.scrollTo({
        left: this.el.nativeElement.scrollLeft + 200,
        behavior: 'smooth',
      })
    }, 180);
    }
  }

  clearIntervalRepeater(){
    console.log('clearing');
    clearInterval(this.repeater);
  }

Issue: The scrolling is not smooth and has glitches. I'm seeking assistance in finding the right interval timing or exploring alternative methods to achieve a smoother scroll effect. Can someone help me with this?

Answer №1

Give it a try without using the scroll behavior feature. When the scroll behavior is enabled, it smoothly scrolls to the specified position but then abruptly stops before starting again. To address this issue, manually set the scroll position and adjust the interval and steps for optimal frame rate:

scrollTo(position, event: MouseEvent){
    if(position == 'left'){
      console.log('left');
      this.repeater = setInterval(() => {
        this.el.nativeElement.scrollLeft -= 5;
      }, 10);
    } else {
      this.repeater = setInterval(() => {
        console.log('right');
        this.el.nativeElement.scrollLeft += 5;
      }, 10);
    }
}

By making these adjustments, you can achieve a consistent speed of movement that appears seamless.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for Deactivating a Button Following a Single Click

I am currently developing a react-native app and I'm in need of assistance with my code stack. My requirement is to disable a button after it has been clicked once. Can anyone provide guidance on this issue? The challenge I am facing is that I cannot ...

Angular Material design failing to display properly

Despite following the Angular Material guide on their website, I am still unable to see the gestures and design properly. I have meticulously followed all the steps outlined in the Angular Material guide. HTML <mat-radio-group> <mat-radio-but ...

Retrieving radio button values in React from a different component

I am dealing with a child component that contains radio buttons, each with its own value. I have imported this child component into a parent component to manage its state from the parent component. With the child component added, I need to access all the i ...

Retrieve properties of the chosen MenuItem from a Select component in Material UI

My custom component const myUniqueComponent = ({ title, data, errors, onSubmit, groups }) => { const [state, setState] = useState( Object.assign( { username: "", password: "", group: "", isAdmin: false, ...

The TypeScript type 'Record<string, string>' cannot be directly assigned to a type of 'string'

I can't seem to figure out why this code isn't working. I've encountered similar issues in the past and never found a solution. The snippet goes like this: type dataType = { [key: string]: string | Record<string, string>; ...

Sorting through a collection of subarrays

Within my application, the structure is set up as follows: [ ["section title", [{ item }, { item } ... ]], ["section title", [{ item }, { item } ... ]], ... and so forth When displayed in the view, the sections are placed in panels, with their internal ...

Using separate files for routes in Express.js can help organize and streamline your code

I'm facing an issue while setting up a node project where I need to organize my files. Specifically, I want to place a file routes.js within the routes/routes.js directory and controllers files in the controllers/ directory. For instance, let's ...

What is the process for specifying the type for the createApp(App) function in Vue.js 3?

I'm currently working with Vue3 and Firebase using TypeScript. // main.ts import { createApp } from 'vue' import App from './App.vue' import './registerServiceWorker' import router from './router' import store f ...

Issue with Color in Line Chart of Flot Version 0.8.2

While working on Flot line charts and customizing their colors, I came across a strange issue. Once I set the first 3 colors, the plot started using the last color for all the remaining lines. This behavior was unexpected and not the norm. What adds to th ...

Placing the IconButton within an AppBar Component using React-JS

Trying to position two IconButtons within a Toolbar, one on the right side and the other on the left side. However, both are ending up on the right side. Here's my code: <AppBar position="fixed" > <Toolbar> <Ic ...

Ways to make the input field appear invalid without the use of forms, causing the bottom outline to turn red when a specific condition is met

Currently, the application does not utilize any forms. I am interested in making the input field invalid under certain conditions within the component. For example, if a user leaves the input field blank, I would like the bottom outline to turn red when an ...

When activated, JavaScript is producing an undefined response

This is a function with the following designer code. I have made updates to include the latest answer. function OnClientLoBChecked(sender, args) { var ChkBoxLOB = document.getElementById("<%= cbFLoB.ClientID %>"); var ChkBoxDis = document ...

issue with mat-select in a dialog not functionering correctly

In my current project, I am working on implementing a feature that requires the user to select an option from a drop-down menu and confirm their choice by clicking an "OK" button. To achieve this functionality, I am utilizing Angular Material. However, I h ...

Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular? var addProductModule = angular.module("addProductModule", []); addProductModule.factory("addProductService", ['$http', function ($http) { return { function savePro ...

Exploring the Functionality of Using Multiple Middlewares in Vue.js 3

For my web app project using vue.js 3 and vue-router, I followed a helpful tutorial on implementing middleware pipelines. The tutorial can be found at: https://blog.logrocket.com/vue-middleware-pipelines/. This tutorial demonstrated creating middleware to ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...

The WebSocket connection in the browser, when accessed through a remote server, typically shows a CLOSED state in the readyState property during the on

Local server operations are running smoothly. However, when testing on a remote server with Nginx, the issue arises where the readyState inside the event handler onopen is consistently showing as CLOSED. Nginx configuration: server { server_name doma ...

What is the best way to incorporate a new field into an established JSON structure?

I have a JSON data set containing 10,000 unique records and I am looking to add another field with a distinct value to each record. What is the best way to achieve this? [ { _id: "5fffd08e62575323d40fca6f", wardName: "CIC", region: &quo ...

The inferred type of a TypeScript promise resolved incorrectly by using the output value from a callback function

Although some sections of the code pertain to AmCharts, the primary focus of the question is related to TypeScript itself. The JavaScript functions within the AmCharts library perform the following tasks: export function createDeferred(callback, scope) { ...