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

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

the ajax success function is malfunctioning

I'm encountering an issue with my ajax function. I am trying to change the CSS for certain HTML elements on 'success', using the following code: success:function(d){ $('#name').css('weight','normal'); ...

Conceal mobile button

Welcome to my website: Is there a way to hide the button on mobile phones? I want to create different buttons specifically for mobile devices. Below is the HTML code for the buttons. HTML <a href="http://site9171756.91.webydo.com/Info.html" target="p ...

Is there a way to transmit a div using Node.js?

Scenario: I am developing a web application that allows users to draw on a canvas, save the drawing as an image, and share it with others using Node.js. Current Progress: Drawing functionality (real-time updates on both clients). Saving the canvas as a ...

Is there anyone who can provide a straightforward solution (code) for < something basic?

I have learned a lot about programming, but I'm stuck on one thing. How can I make an image stay in place when clicked on? What I mean is that when you click and hold on the image, then move the cursor, the image moves with the cursor. What I want is ...

The alignment of flexNav.js submenus is not consistent

I'm looking to implement the Flex Navigation plugin for a responsive menu. Although the plugin functions properly, I'm encountering an issue with the alignment of submenus under their respective parent items. You can view the problematic behavi ...

Activating the Isotope

Apologies if you've come across this issue previously. This is the third time I am attempting to solve it, and so far, most of my work has been focused on identifying the root cause. The goal of my project is to load a sequence of images and offer a ...

The dropdown functionality in Bootstrap appears to be malfunctioning

Struggling to make the drop-down menu function properly in Bootstrap, but so far no success. Check out the code on this jsfiddle link. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="dropdown01" data-to ...

Obtain the height and width of the original images from the href and assign them to your attributes using jQuery

Hey there pals, I'm currently on a mission to fetch the dimensions (height and width) of an image from a hyperlink and then insert those values into its attribute. This task has got me going bonkers! Here's my snippet: <figure> <a ...

Is there a way to delete a table row and then set a background color for every other table row that remains?

After the document has loaded, I used jQuery to set the background color of every even-row table row to orange. Later, I added a button that executes the code: $("#tr3).remove() which deletes the third row with an ID of "tr3". Following this removal, I t ...

How can one use jQuery to target elements that have names that are in an array format?

Is there a way to retrieve the values of these elements and send them as an array using ajax? <input type="checkbox" name="Broadcast[m]"/> Members <input type="checkbox" name="Broadcast[i]"/> IATA agencies <input type="checkbox" name="Bro ...

How can I adjust the size and width of the autofocus cursor inside an input box using Angular?

How can I modify the height and width of the cursor in an input field with auto focus? app.component.html <input class="subdisplay" [ngModel]="input | number" type="text" (keyup)="getValue(box.value)" name ...

Vue JS encounters difficulties when attempting to lazy load various images from a randomized image URL

I've implemented a code snippet for lazy loading images with different URLs: <img src="https://source.unsplash.com/1600x900/?hotel,booking.com?v=1" loading="lazy" /> <img src="https://source.unsplash.com/1600x900/?hot ...

What is the simplest method for transferring data to and from a JavaScript server?

I am looking for the most efficient way to exchange small amounts of data (specifically just 1 variable) between an HTML client page and a JavaScript server. Can you suggest a script that I can integrate into my client to facilitate sending and receiving d ...

ion-grid featuring alternate columns

As someone who is not very familiar with Angular, I am trying to create a grid layout like the one shown here: https://i.stack.imgur.com/nBavk.png The desired layout includes alternating rows with one image followed by two images. My current attempt at a ...

Practical Guide to Implementing Ajax and JSON Encoding in Zend Framework 2

Having an issue with a simple ajax application using jQuery where every data object is returning as null. Can someone assist me in resolving this? protected $mysqlAdapter; protected $studentid; protected $fullname; protected $birthdate; protected $placebi ...

`Is it challenging to convert JSON into HTML, leading to undefined results?`

I am currently attempting to extract YAHOO data by utilizing getJSON and YQL. Although the connection is successful, I can retrieve the data and log it in the console. However, I am facing difficulties when trying to display this data on the JSP page I am ...

Issues with displaying images in CSS when using HTML 5 canvas drawing

In attempting to draw an image on a canvas using a pre-loaded image and CSS, such as: img.style.backgroundColor="red"; ctx.drawImage(img,0,0,100,100); I have observed that the image is drawn without incorporating the CSS modifications. Are HTML canvases ...

Automatic placement of the cursor at the left end of the username field in the registration form is required

Hey there! I'm looking to customize the registration form on my WordPress website so that when a user clicks on any field, such as the username field, the cursor automatically moves to the left end of that field and the keyboard switches to ENG-US. ...

Bootstrap's landing page problem

I am currently working on creating a landing page using bootstrap and have encountered an issue with the text alignment in my section containing icons and tags. In order to make the text appear clean and concise, I want the text to be displayed in either o ...