The setInterval() function causing unusual overlapping issues

While experimenting with creating a basic text carousel, I encountered a puzzling issue that has me stumped.

The structure of the carousel is straightforward. It consists of a wrapper and the actual text to be cycled through.

Unfortunately, the problem appears to stem from the setInterval method. When the animation completes its cycle and loops back to the beginning, there is an odd overlap between the first and second texts displayed. The initial text animates as expected but then briefly reappears to replace the second text.

If anyone could shed light on why this error is occurring in such a way, I would greatly appreciate it.

let animateSlide = setInterval(moveSlide, 1200);

function moveSlide() {
  let carousel = document.getElementById("wordCarousel");
  let firstSlide = carousel.children[0];
  let createID = document.createAttribute("id");

  createID.value = "active";

  firstSlide.setAttributeNode(createID);

  carousel.appendChild(carousel.firstChild);

  carousel.children[carousel.children.length - 1].removeAttribute("id");
}
/* Carousel Styles */

#wordCarousel {
  height: 36px;
  overflow: hidden;
}

.carouselSlide {
  color: #555;
  font-size: 36px;
}

#active {
  margin-top: 0px;
  animation-name: example;
  animation-duration: 1.2s;
  animation-timing-function: ease;
}

@keyframes example {
  from {
    margin-top: 0px;
  }
  to {
    margin-top: -40px;
  }
}
<div id="wordCarousel">
  <div class="carouselSlide">
    Item 1
  </div>
  <div class="carouselSlide">
    Item 2
  </div>
  <div class="carouselSlide">
    Item 3
  </div>
  <div class="carouselSlide">
    Item 4
  </div>

</div>

Answer №1

Avoid using setInterval for CSS animations as it may lead to synchronization issues. Instead, consider utilizing events like animationiteration, animationend, or animationstart.

Here's a more efficient approach with less code and easier management.

let carousel = document.querySelector('#wordCarousel div');

carousel.addEventListener('animationiteration', () => {
  carousel.appendChild(carousel.children[0]);
});
#wordCarousel {
  height: 36px;
  overflow: hidden;
}

.carouselSlide {
  color: #555;
  font-size: 36px;
  line-height:100%; /* ensuring the height is equal to 36px */
}

#wordCarousel > div {
  height:100%;
  animation: example 1s infinite;
}

@keyframes example {
  to {
    transform: translateY(-100%);
  }
}
<div id="wordCarousel">
  <div>
    <div class="carouselSlide">
      Item 1
    </div>
    <div class="carouselSlide">
      Item 2
    </div>
    <div class="carouselSlide">
      Item 3
    </div>
    <div class="carouselSlide">
      Item 4
    </div>
  </div>
</div>

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

Should you consider using the Singleton pattern in Node.js applications?

After stumbling upon this specific piece discussing the creation of a singleton in Node.js, it got me thinking. The require functionality according to the official documentation states that: Modules are cached after the first time they are loaded. Multi ...

Looking for the Mustache template library?

Can you provide some examples of how mustache can be used effectively? I recently came across it, but I'm struggling to grasp how it differs from the traditional approach of creating template files within frameworks like cakePHP or django, or simply ...

Generating a File that Imports Components and Instantly Exports Them Once More

Having trouble with this code. Initially, I had: // file 1 import Box from '@/components/Box' import Popup from '@/components/Popup' const MDXComponents = { Box, Popup } // using MDXComponents somewhere in file 1 Now, to manage t ...

Trouble arises when dealing with components beyond just the background while using jquery_interactive_bg.js

After experimenting with different plugins, I managed to achieve a parallax effect on my website's landing page by using the interactive_bg.js plugin. Following the steps outlined in a demo tutorial, I was able to attain the desired visual effect. Be ...

JavaScript - overriding or halting the execution of code

I'm currently working on a project for a client where I need to incorporate their header and footer, along with some essential JavaScript files. The issue I've run into is that one of the core JS files they provided is poorly written - it fails t ...

Styling Your PHP Output with Echo

Is there a way to create a compact text box with a scroll bar that can display recurring data generated by PHP activities on the server side? How can I format it in this way? ...

Ways to verify the nodemon version that is currently installed on your local machine

On my Windows 10 machine, I recently installed nodemon locally in a project and now I'm curious to know which version is installed. Can someone please share the command to check the version of nodemon without needing to install it globally? My aim is ...

Executing a post request asynchronously and storing the retrieved data into a variable

Currently, I am in the process of learning AngularJS and attempting to upgrade my current method of fetching data from a web service and dynamically assigning it to a variable that is binded using ng-repeat. My main objective is to implement an asynchronou ...

Forcing a property binding update in Angular 2

Take a look at this particular component import {Component} from 'angular2/core' @Component({ selector: 'my-app', providers: [], template: ` <div> <h3>Input with two decimals</h3> <input type ...

Tips for creating JSON using AngularJs to store tabular information

I successfully created an HTML page using AngularJS. <form name="target" ng-submit="createAllKeywordsJSON(codeMasterList)"><!-- createAllKeywordsJSON() --> <input type="submit" value="Save" class="myButton" name="submit" style="margin: ...

Retrieving the value of onCheck from the Checkbox/ListItem

Imagine I have a React.Component that displays components from material-ui: {data.map(value => ( <ListItem key={data.indexOf(value)} primaryText={value} leftCheckbox={ <Checkbox onCheck={this.pr ...

Add a border to the image when the radio button is selected

I am attempting to add a border to an image when a radio button is checked. Here is the HTML code I am working with: <div class="frm_radio"> <label for="field_n9r1a2-0"> <input type="radio" name="x" id="t" value="Betreuung"> B ...

Once you address a block using jQuery

$(function(){ $(window).scroll(function () { var scrollVal = $(this).scrollTop(); var adscrtop =$(".header").offset().top // 在 RWD 767以下不作動 if(window.screen.width>767){ if(sc ...

Vue: Changing the value in the select dropdown causes input fields to reset their content

After setting up a form with input values, I noticed that when using a select element with a v-model to change the dropdown value, the input fields from the previous selections are cleared. This has been a persistent issue for me and is now starting to imp ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

Operating on an angular table arr with the splicing of an object attribute

Encountering an issue. I have a component with some logic for creating and deleting input fields .ts export class AppComponent implements OnInit { resource: Resource[] = []; fieldId = 0; testArr = ['1', '2', '3', ' ...

React approach for managing multiple combobox values

Currently, I'm working on a page where users can upload multiple files and then select the file type for each file from a dropdown menu before submitting. These 'reports' are the uploaded files that are displayed in rows, allowing users to c ...

What is the process for uploading an HTML input file in segments?

Is it possible to upload the whole file at once like this: myInput.onchange = ({ target }) => { const file = target.files[0]; const formData = new FormData(); formData.append("fileData", file); // ...then I post "formData" ...

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

Transferring information to modal without using AngularUI

I'm currently working on an Angular application and facing an issue with passing data from my controller to a modal. Here is the HTML code on my index page: <!DOCTYPE html> <html lang="en" ng-app="myApp"> <head> ... </head> & ...