Steps for making a CSS animation that horizontally moves an element

I've been working on a React project that features a horizontally scrolling banner. The animation for the automatic scroll is set up like this:

  "@keyframes marquee": {
    "0%": { transform: "translateX(0);" },
    "100%": { transform: "translateX(-100%);" },
  },

The issue I'm facing is that users should be able to manually hover over the banner and scroll it themselves. To enable manual scrolling, I added the following code snippet:

pingsSectionRef.current.addEventListener("wheel", (event) => {
  event.preventDefault();
  const scrollAmount = 10;
  if (pingsSectionRef.current)
    pingsSectionRef.current.scrollLeft +=
      event.deltaY > 0 ? scrollAmount : -scrollAmount;
});

However, I encountered a problem where the scrolling only works in one direction. Content that goes off-screen doesn't reappear when scrolling back (possibly due to the translateX animation). How can I allow scrolling in both directions?

Answer №1

It seems like you have implemented an auto-animation using CSS along with a "wheel event" to control it.

Here are some suggestions that you can consider:

  1. Try approaching it the "React way": Instead of manually adding an event listener, handle the state programmatically.
  2. You could toggle a class to start or stop the auto-scroll animation.
  3. If you require more precise control, utilizing a library such as Framer Motion might be beneficial.

Below is an example showcasing how you could implement these suggestions:


const Banner = ({ images }) => {
  const [isAutoScroll, setIsAutoScroll] = useState(true);

  const onHoverHandler = () => setIsAutoScroll(false);
  const onBlurHandler = () => setIsAutoScroll(true);

  return (
    <div
      className="container"
      onMouseEnter={onHoverHandler}
      onMouseLeave={onBlurHandler}
    >
      <div className={`scrolleable ${isAutoScroll ? "play" : "pause"}`}>
        {images.length > 0 &&
          images.map((img) => {
            return <ImageBanner key={img}> {img} </ImageBanner>;
          })}
      </div>
    </div>
  );
};

For styling in CSS:


.scrolleable {
  display: flex;
  position: relative;
  animation-name: marquee;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

.play {
  animation-play-state: running;
}
.pause {
  animation-play-state: paused;
}

@keyframes marquee {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}

Remember to customize this approach according to your specific requirements or technology stack.

Alternatively, you can explore handling the position of the marquee element programmatically without relying solely on CSS by adjusting the property scrollLeft. This method may involve managing the positioning at various touchpoints and ensuring proper cleanup functions to prevent memory leaks. Your component would need to handle incrementing or decrementing the position based on scrolling behaviors and mouse interactions.

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

Experimenting with a sample post on a minimalist Node.js application using Mocha and Superagent

I trust you are having a splendid day. Currently, I am focusing on enhancing my TDD skills in Node.js. To practice, I have developed a minimalistic application that handles basic GET and POST requests. The app simply displays a straightforward form to the ...

Tips for displaying the Material UI Menu component on the left side instead of the default right side

Recently, I created a dropdown component using Material UI's Menu component. However, the default behavior of the menu is to open towards the right side. I actually need it to open towards the left instead. I attempted to modify its styling, and whil ...

Unlock the Power of jQuery Hashing with the Addition of Additional Variables

Looking for a way to include an additional variable in a URL like the one above. I've experimented with different methods but I'm not certain which is the most effective. For example: Currently using JQUERY to detect the HASH value: if (window ...

Testing D3js functionality within a React component with the help of Jest and Enzyme

Issue: Upon running my code, the SVG successfully appends to the outer div on the component and displays on the page as expected. However, while testing, the SVG fails to append to the outer div. Technology Stack: I am currently attempting to test my d3js ...

What are some ways to create a responsive Grid in React JS with the help of Bootstrap?

Utilizing bootstrap in my react js project, I am implementing css grid to showcase some cards. However, I am encountering responsiveness issues. import React from "react"; import "./Project.css"; export const Project = () => { return ( <div& ...

The HTML document is unable to locate the Angular framework

I'm encountering an issue with the code below on my HTML page - every time I run it, I receive an error message saying "angular is not defined". I've already included angular in the head section of the page so I'm puzzled as to why it's ...

JavaScript access to local files

I am currently utilizing Pannellum, a free panoramic viewer that is built on HTML5 and JavaScript. The application functions properly when the image is hosted online, but it encounters issues when trying to access local files (for example, having an HTML ...

Combining the jQuery Rateyo plugin with AngularJS for rating integration

I've been working on integrating the Rateyo plugin with AngularJS, but I'm facing an issue in extracting the rating value from the directive. Below are the snippets of my code: EDIT: Check out the functional plunker Controller var app = angula ...

The Bootstrap modal stubbornly refuses to close even after resetting the HTML body

I am having an issue with my bootstrap modal where the closeModal button is not functioning properly after the printModal button has been clicked. The modal does not close as expected. Step 1: Click on the printModal button after the modal pops up (this w ...

Perform a jQuery computation using a CSS style

Having trouble with a calculation using a CSS property that is not returning any value. Seems like the issue might be due to the CSS property returning '200px' instead of just '200'. Any suggestions for a workaround? Thanks in advance. ...

Can components in Vue.js share functions?

Within my application, there exists a plethora of utility functions that handle various tasks such as parsing strings and displaying toasts. My main inquiry is regarding how to access these functions within other .vue files without the need for redundant ...

Relay: Constructing nested fragments

When using react-router: <Routes> <Route path="/" component={App}> <Route path="about" component={About} /> <Route path="help" component={Help} /> </Route> </Routes> Within the App component: render() { r ...

Uncovering concealed data in job listings by utilizing BeautifulSoup

Hey there! Currently, I am enrolled in a python course and our assignment for today involves extracting job listings from this website: I have attached a screenshot of the HTML related to this task here: python jobs f12 This is what I have managed to com ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...

Is it more effective to retrieve data periodically or through SSE/websockets?

My goal is to introduce server-sent events (SSE) for notifications, allowing users to receive real-time updates. However, I'm curious about the drawbacks of fetching data at regular intervals in my frontend. Is this not a viable option? Why do develop ...

Organize an array of objects with underscore.js to arrange them in a

I have an array of objects that looks like this: profData=[{"Details":{"CODE":"PAT4PAS","DESCRIPTION":"PASTIE 4N20 12 X 175G","LOCATION":"FREEZER","UNITS":"BOX","WAREHOUSE":"00","AVAILABLE":"15.0000","ON_HAND":"15.0000","BRAND":"4N20","PRICE1":"18.80"," ...

Error encountered when trying to upload a file to Django: KeyError or MultiValueDictKeyError

Having trouble sending form data with a file to a Django API through AJAX? When the MultiValueDict is empty, you might run into KeyError for the file. Check out this code snippet to see how it's implemented: index.html [Front End] <button type="b ...

Expanding ChartJS canvas width to align with excessive columns within Bootstrap framework

I am working on a simple Bootstrap document with 2 rows. The first row has a variable number of columns that overflow horizontally, and the second row contains a chart that needs to be responsive to match the number of columns in the top row. It appears t ...

Passing hooks down in React leads to input losing focus due to rerendering

I have a parent component where I initialize some state, and then pass it down to the child components for updating. Unfortunately, when the update occurs, the component tree is re-rendered causing my inputs to lose focus. Even adding a `key` did not resol ...

Intellisense in VS Code is not functioning properly for vitest matchers

After transitioning my codebase from cra to vite and integrating vitest, everything seems to be running smoothly. However, I am encountering an issue with suggestion prompts in VS Code while performing assertions such as expect(getByText(text)).toBeInTheDo ...