Stopping or pausing the scrolling items at their current position when the mouse hovers over them, and then resuming when the mouse leaves

In my React page, I am attempting to create an infinite scroll list of items that starts at the bottom and ends at the top of a div.

While I have been able to achieve circular scrolling, I am struggling with pausing the scroll when the mouse hovers over the items. They continue to scroll despite the hovering.

As someone new to JS, I need help in implementing a feature that will pause the items in their current positions when the mouse hovers over them, and resume scrolling once the mouse leaves.

Here is the JSON dummy data string:

data =  [{"item0":10},{"item1":11},{"item2":12},{"item3":13},{"item4":14},{"item5":15},{"item6":16},{"item7":17},{"item8":18},{"item9":19}];

React code:

(Code remains unchanged) 

dashBoard.css

.alerts-header {
  text-align: center;
  font-weight: bold;
  margin-bottom: 10px;
}
.alerts-container {
  position:relative;
  height:100%;
  overflow:hidden;
}

(Styles remain unchanged)

.dashboard_alertBarChart {
  width: 45%;
  background-color: #1eeeee1a;
  border-radius: 10px;
  margin-top: 1%;
  position: relative;
  overflow: hidden;
}

Screenshot:

https://i.sstatic.net/oFGqo.png

I have attempted some solutions but require assistance in halting the scrolling effect when the mouse hovers over the items.
Thank you for your help.

Answer №1

If you're looking for a way to access the scroll animation applied through CSS in your web project, consider using the Element.getAnimations() method to retrieve the corresponding Animation object. Once you have obtained this object, you can utilize the .pause() and .play() functions as required:

const { useEffect, useState, useRef } = React;

const ScrollChart = () => {
  const [data, setData] = useState([]);
  const alertListRef = useRef(null);
  const scrollSpeed = 1;
  const [isHovering, setIsHovering] = useState(false);
  const [shouldScroll, setShouldScroll] = useState(true);
  let scrollRef = null;
  
  useEffect(() => {
    const fetchData = () => {
      try {
        //dummy data used
        const jsonStr = '[{"item0":10},{"item1":11},{"item2":12},{"item3":13},{"item4":14},{"item5":15},{"item6":16},{"item7":17},{"item8":18},{"item9":19}]';

        setData(JSON.parse(jsonStr));
      } catch (error) {
        console.log("Error-- " + error);
      }
    };

    fetchData();
  }, []);

  const handleMouseEnter = () => {
    setIsHovering(true);
    alertListRef.current.getAnimations()[0].pause();
  };

  const handleMouseLeave = () => {
    setIsHovering(false);
    alertListRef.current.getAnimations()[0].play();
  };

  return (
    <div className="dashboard_alertBarChart" >
       <div className="alerts-header">Alerts</div>
       <div className="alerts-container" onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}>
          <div className="alert-list" ref={alertListRef}>
             {data.map((alert, index) => {
               const severity = alert.severity || 'medium'; // Set default severity as 'medium' if not found
               return (
                 <div key={index} className="alert-item">
                   <div className={`legend-box ${severity}`}></div>
                   {Object.keys(alert)[0]}: {Object.values(alert)[0]}
                 </div>
               );
             })}
          </div>
       </div>
    </div>
   );
};

ReactDOM.createRoot(document.getElementById('app')).render(<ScrollChart/>);
.alerts-header {
  text-align: center;
  font-weight: bold;
  margin-bottom: 10px;
}
.alerts-container {
  position:relative;
  height:100%;
  overflow:hidden;
}

.alert-list {
  overflow-y: auto;
  animation: scroll 20s linear infinite;
  scrollbar-width: thin;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  scrollbar-width: thin;
}

.alert-item {
  font-weight:bold;
  padding-bottom:10px;
  color:#09094a;
}

@keyframes scroll {
  0% {
    transform: translateY(100%);
  }
  100% {
    transform: translateY(-100%);
  }
}

.legend-box {
  width: 14px;
  height: 14px;
  display: inline-block;
  margin-right: 5px;
}

.high {
  background-color: red;
}

.medium {
  background-color: yellow;
}

.low {
  background-color: green;
}

.dashboard_alertBarChart {
  width: 45%;
  background-color: #1eeeee1a;
  border-radius: 10px;
  margin-top: 1%;
  position: relative;
  overflow: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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

How can I change the "Return" button on the iOS keyboard to a "Next" button using jQuery or JavaScript?

Currently, I am developing an HTML application and working on implementing it for IOS devices such as the IPAD. Within my application, there are multiple text boxes. Whenever a user clicks on a text box to input text, the keypad appears. On this keypad, ...

The process of sharing a complete full-stack (ReactJS, NodeJS, socketIO) project on GitHub using Git Bash command line

Recently, I completed a project on realtime chat and now I am looking to upload it to my GitHub repository. My folder structure is as follows: enter image description here I am currently unsure how to upload the entire project to GitHub using git bash com ...

Tips for updating Ref objects in React

In the process of fixing a section of my project, I'm encountering an issue where I have no control over how refs are being utilized. The Editable text elements are currently handled through refs and a state variable within the component that holds al ...

What is the correct method for iterating through this array of objects and eliminating those with either null or empty item.text values?

Currently, I am working with the following Array: const contactInfo = computed(() => { return [ { id: 'address', icon: 'detail/clubLocation', text: `${props.data.contactInfo.address}` ...

Tips for sharing a post with an image through the addThis plugin in jQuery

Can anyone help me figure out how to share a post on Facebook using AddThis while including the image and caption? I've written some code to share on Facebook, Twitter, and email but I'm having trouble getting the image to show up. This is what I ...

Utilizing a Nodemailer template with a JSX/React component: A step-by-step guide

Currently utilizing Next.js with Nodemailer, my goal is to incorporate React / JSX components as templates in Nodemailer. In my current setup for Nodemailer, I have to manually write the HTML template like this: html: ` <div style="h ...

I need to display the product name associated with the product_id found in the line_items array within the order table. I aim to achieve this functionality by utilizing Laravel with Vue.js

In my database, there is a cell called line_items in the orders table that contains data like: [ {"customer_id":"30","product_id":"10","unit_id":"2","quantity":"1","price":"2700","total_price":"2700"}, {"customer_id":"30","product_id":"43"," ...

Discovering the method for accessing nested JSON data through ng-repeat in AngularJS

I'm attempting to access the items._id value within ng-view using ng-repeat. I am able to retrieve all data, but I am interested in specific data only. Data.json [ { _id : "td6v9db4514cc4ewew4334", firstName : 'ayaz', la ...

Navigating with Reach Router only updates the URL, not the component being rendered

Is there a way to programmatically navigate using Reach Router in React? I have noticed that when updating the URL, the route does not render. Even though the URL changes, the original component remains displayed according to the React developer tools. Ho ...

The module 'fs' cannot be resolved by Webpack Express due to an expression dependency in the request

Every time Express is added to my project, I encounter these errors during the webpack build process. webpack.config.dev.js var path = require("path") module.exports = { entry: { "server": "./server/server.ts" }, output: { path: path.resol ...

Creating custom annotations for specific fields in jsonschema2pojo

I've encountered a situation while using jsonschema2pojo where some fields require special serialization and deserialization. How can I configure this in the json schema? Here is my current schema: "collegeEducation": { "javaJsonView ...

Creating a responsive design for a centered image with absolute positioning

I'm trying to align an image at the bottom of a div while also centering it using the following CSS: HTML: <div class="myDiv"> <img src="http://bit.ly/1gHcL8T" class="imageCenter" /> </div> CSS: .myDiv { width: 80%; height: ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

The redirection from HTTP or www to HTTPS is not functioning as expected

Redirecting all links to my website to the https:// domain is supposed to work flawlessly, but there are certain ways it doesn't quite function as expected. https://www.example.com --- works example.com --- works www.example.com --- encounters issu ...

The CSS remains dormant until the cursor is hovered over

Let's kick things off with a quick video presentation. Check out this video for more details In the video, you can observe that when opening the dropdown menu on the top right corner, all Tailwind Classes seem to be missing. It's puzzling why t ...

Rendering data from the server using backbone.js: A comprehensive guide

Initially, this is the response received from the server $response = array(); $i = 0; while($result = mysql_fetch_assoc($query)){ $response[$i]["id"] = $result["ID"]; $response[$i]["post_ ...

accommodating multiple background images in CSS

I am currently working on a WordPress website using the Twenty Twelve theme. On one of the pages, I am trying to incorporate three background images - one at the top, the next one right below the top image, and the third one at the very bottom... Is there ...

Video streaming platform without the need for javascript and plugins

Is it feasible to watch Youtube videos without relying on javascript and plugins, exclusively using HTML5 or a similar alternative? ...

What is the best way to eliminate the `<option>` tags nested within a `<select>` element using

Here is the code snippet I am working with: <select> <option>option1</option> <option>option2</option> <option>option3</option> </select> I need to remove one of the options from this select men ...

Using Node.js and DIME to send binary data via POST requests

After reading a file that is 1740 bytes long into a Buffer called res, the length of res.length and res.toString('binary', 0, res.length).length is both determined to be 1740. A POST request is then sent using the request library. request.post ...