Is it necessary to create a separate animation class to trigger CSS keyframe animations based on scroll position?

My website has a background animation that controls various shapes, each with their own unique animation styles:

animation: animShape 50s linear infinite;

The speed of the animations varies depending on the shape being displayed.

The animShape keyframes are defined as follows:

animShape {
from {
transform: translateY(0px);
}
to {
transform: translateY(-2000px);
 }
}

I am looking to adjust the speed of each shape (represented by div elements) based on the scroll position.

I have been considering different approaches and was hoping for some guidance in the right direction.

Here's an idea I had:

$(document).on('scroll', '#section-trigger' , function(){              
$("#first-shape").removeClass('.first-animation-class');
$("#first-shape").addClass('.second-animation-class');})


$(document).on('scroll', '#another-section-trigger', function() {
$("#first-shape").removeClass('.second-animation-class');
$("#first-shape").addClass('first-animation-class');})

...

However, this approach would require me to create separate animation classes for each shape, which might not be the most efficient way to handle it.

Another option could be utilizing JQuery to manage all the animations, but I've read that it may not have direct access to :after elements. Any workarounds for this issue?

Apologies if the formatting is off – sometimes it gets confusing. Appreciate any help!

Answer №1

I created a dynamic animation that responds to scrolling and incorporated a timer to coordinate the start and finish of the animation.

Ensure that each animation aligns with the designated timer interval. For instance, I set up an animation to run for 2 seconds, repeated twice, resulting in a total duration of 4 seconds per cycle.

By making slight adjustments to the structure, you can implement various animations seamlessly

let timer;
var timerCount = 0;
MyTimer();
var element1 = document.getElementById("myDIV1");
var element2 = document.getElementById("myDIV2");
function doSomething() {
  
  if(!element1.classList.contains('anim1'))
      element1.classList.add("anim1");

  if(!element2.classList.contains('anim2')) 
      element2.classList.add("anim2");     
}


function MyTimer()
{
    timerCount = timerCount + 1;
    if(timerCount >= 5)
    {
     
      if(element1.classList.contains('anim1'))
         element1.classList.remove("anim1");
      if(element2.classList.contains('anim2'))
         element2.classList.remove("anim2");
         
       timerCount = 0;
    }
    timer = setTimeout(MyTimer, 1000);
}


document.addEventListener('scroll', function(e) {
 doSomething();
});
body{
   height:2500px;
}
.shape1{
  width: 50px;
  height: 50px;
  background-color: red;
  position: relative;
  float:left;

}
.shape2{
  width: 50px;
  height: 50px;
  background-color: red;
  position: relative;
  float:right;
}
.wrapper{
   width;100%;
   border:1px solid #ddd;
   padding:20px;
   margin:150px 20px;
   height:150px;
}
.anim1 {
  animation-name: example1;
  animation-duration: 2s;
  animation-iteration-count: 2;
  animation-direction: alternate;  
}

.anim2 {
  animation-name: example2;
  animation-duration: 2s;
  animation-iteration-count: 2;
  animation-direction: alternate;  
}

@keyframes example1 {
  0%   {background-color:red; left:0px; top:0px;}
  25%  {background-color:yellow; left:100px; top:0px;}
  50%  {background-color:blue; left:100px; top:100px;}
  75%  {background-color:green; left:0px; top:100px;}
  100% {background-color:red; left:0px; top:0px;}
}

@keyframes example2 {
  0%   {background-color:red; right:0px; top:0px;}
  25%  {background-color:yellow; right:100px; top:0px;}
  50%  {background-color:blue; right:100px; top:100px;}
  75%  {background-color:green; right:0px; top:100px;}
  100% {background-color:red; right:0px; top:0px;}
}
<div class="wrapper">
    <div id="myDIV1" class="shape1"></div>
    <div id="myDIV2" class="shape2"></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

Ways to activate a different jQuery event by utilizing the output from a previously run jQuery event

I have a button on my website that looks like this: <a id="btn" class="button">Click Me!</a> When this button is clicked, it triggers a jQuery function as shown below: $("#btn").on("click", function() { $.ajax({ url: 'index.php&ap ...

Sharing data with external domains and retrieving HTML output using JavaScript

When a browser sends a POST request and expects an HTML page result from JavaScript, problems arise if there is no Access-Control-Allow-Origin in the server response. Unfortunately, changing anything on the server side is not an option. If a human clicks ...

Issues with Ajax.BeginForm causing JSON to be returned as undefined (Confirmed by Dev Tools)

I'm facing a strange issue while attempting to retrieve a basic JSON object from my controller. Although I can see the JSON returned perfectly fine in Firefox debug tools, when I look at my javascript callback, I receive an undefined in my console.log ...

Utilize Cordova to download files and access them within the Cordova framework

Apologies for my lack of knowledge, any guidance or assistance in the right direction would be highly valued. I am working on a small application that retrieves data from an API using json requests. One of the functionalities required is to download a spe ...

Tips for creating custom CSS to target a specific element within a group of similar elements

My cssSelector for locating elements is div.formErrorContent. There are 4 matched elements, but I need to pinpoint the first element. Can anyone assist me with this? I am aware of how to write the xpath code for this: (//div[@class='formErrorContent ...

Looking for a way to ensure a div reaches 100% height within a specified area without exceeding the boundaries of the body?

I am working with jQuery mobile and have specific requirements for my project: The main content will be a large graphic that needs to fill the entire page, with both horizontal and vertical scrolling if necessary. The header should remain fixed at the to ...

The jQuery.addClass() function seems to be malfunctioning

I'm encountering an issue with the addClass() method. For some reason, it's not functioning properly in this scenario: https://jsfiddle.net/0g1Lvk2j/20/ If you scroll to the end and close the last box by clicking on the orange box, the orange b ...

Two vertical divs stacked on top of each other, each expanding to the entire height and width of the browser window

Is there a way to set the width and height of two divs on a webpage to match the dimensions of the browser window, requiring scrolling to view the second div? In addition, how can I ensure that the content within these divs is vertically centered? To ach ...

What occurs when Click events are triggered on an <object> element?

I have set up a div, and inside that container, I embedded an SVG image using object (which I plan to manipulate later...). <div id="click-me"> some random Text <object data="some.svg" /> </div> Next, I added event listeners for t ...

Steps to gather all the images within a directory

Take a look at this demo When you click on the "next" button, new images are loaded from the internet. In my application, all the images are stored in the img/image folder with names like 1.jpg, hi.png, etc. My question is, how can I display these image ...

JavaScript - Capture the Values of Input Fields Upon Enter Key Press

Here's the input I have: <input class="form-control" id="unique-ar-array" type="text" name="unique-ar-array" value="" placeholder="Enter a keyword and press return to add items to the array"> And this is my JavaScript code: var uniqueRowsArr ...

Quirky PHP Chat feature you'll love

I have been developing a jQuery/PHP chat system for my website to facilitate communication among visitors. I anticipate up to 200 simultaneous users on the website, with only 10-20 users actively engaging in conversations. Here's the issue: On rare ...

Is it possible to enclose an image with two <div> tags in a single line?

Can anyone help me with this layout issue I am facing? I have two <div>s wrapping an image in the same row, but for some reason, the right <div> keeps dropping below. I've attempted using float, display:inline-block, and tweaking the styl ...

Steps for troubleshooting a Jquery Dialog

My current jQuery dialog maker is working in most places, but I'm encountering issues when trying to use it for the third time. In this instance, after the dialog is displayed, the form fields become disabled. The core idea behind the code is that th ...

If a quote character is detected in a string, color the line red

My goal is to highlight each line from a string in red if it contains the ">" character. I am applying this logic to a database query result, and while it's successful, I'm encountering an issue where an HTML line break is inserted after each "qu ...

Choose a specific item in jQuery to showcase an error notification

I have the following HTML: $('a[data-action="get-resume"]').click(function(event) { var client_conditions = $('[name="client_conditions"]'); if(client_conditions.prop('checked') == false) { c ...

Display a dropdown menu when hovering over with a delay

I recently created a basic navigation menu with dropdown functionality using CSS3 initially, but I decided to enhance it by incorporating jQuery to display the dropdown after a set timeframe. However, I am facing an issue where all dropdowns appear when ho ...

Is there a difference between innerHTML strings and their corresponding strings in JavaScript?

I am facing an issue with a code snippet that seems to have an unusual error. The following code is a simplified version to demonstrate the strange behavior. <html> <head> <script type = "text/javascript"> window.onload = fun ...

Tips for using JavaScript to style an array items individually

I have currently placed the entire array within a single div, but I would like to be able to display each element of the array separately so that I can style "date", "title", and "text" individually. This is my JSON structure: [ { "date": "Example ...

A step-by-step guide on using Javascript to transform images into text

Hey there! I'm looking for some help to convert an image into text. The idea is that when someone uploads an image and hits the "Submit" button, the text from the image should display in a textarea below. However, the code I've been working on do ...