Loop through each div using jQuery and dynamically add or remove a class to

I am looking to create an infinite loop that adds a class to each div with a timeout in between.

Currently, I have implemented it like this:

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setTimeout(function() {
      $t.addClass('active');
    }, 2000 * i);
  });
});
.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-bordered-box ">
  <a href="#">test1</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test2</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test3</a>
</div>

I want to maintain the same effect but have it loop infinitely so that users always see this animation no matter where they are on the page.

Answer №1

To create a shaking effect, you can utilize the setInterval function and set the interval to be the length of the element multiplied by the timeouts interval, such as 3*2000. Here is an example:

$(document).ready(function() {
  function shakeElement() {
    $('.box').each(function(index) {
      var $elem = $(this);
      setTimeout(function() {
        $elem.addClass('shake');
      }, 2000 * index);
    });
  }
  
  shakeElement();
  
  setInterval(function() {
    shakeElement();
    $('.box').removeClass('shake');
  }, $('.box').length * 2000);
});

.small-box {
  display: block;
  height: 100px;
  width: 80px;
  border: 1px solid #333;
  border-radius: 3px;
  margin-right: 20px;
}

.small-box.shake {
  animation: shakeIt 0.6s linear both;
}

@keyframes shakeIt {
  10%, 90% { transform: translateX(-8px); }
  20%, 80% { transform: translateX(8px); }
  30%, 50%, 70% { transform: translateX(-16px); }
  40%, 60% { transform: translateX(16px); }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-box">
  <a href="#">Item 1</a>
</div>
<div class="small-box">
  <a href="#">Item 2</a>
</div>
<div class="small-box">
  <a href="#">Item 3</a>
</div>

Answer №2

Try using $t.toggleClass('active'); within the setInterval function

$(document).ready(function() {
  $('.small-bordered-box').each(function(i) {
    var $t = $(this);
    setInterval(function() {
      $t.toggleClass('active');
    }, 2000 );
  });
});
.small-bordered-box {
  display: block;
  height: 118px;
  width: 100px;
  border: 2px solid #3e3b38;
  border-radius: 5px;
  float: left;
  margin-right: 35px;
}

.small-bordered-box.active {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;

}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }
  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }
  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }
  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="small-bordered-box ">
  <a href="#">test1</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test2</a>
</div>
<div class="small-bordered-box ">
  <a href="#">test3</a>
</div>

Answer №3

To update your CSS, modify it as follows:

.small-bordered-box.in-motion {
  animation: shake 0.83s cubic-bezier(.36, .07, .19, .97) both infinite;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

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

The PHP language includes a print language construct for outputting text

Having some trouble with a PHP script in my assignment related to page handling. When I submit it through another PHP page, it is showing the actual PHP code instead of executing properly, but it works fine when run standalone. I've created an HTML l ...

Tips on creating reusable scoped styles for 3 specific pages in Vue.js without impacting other pages

Our project includes global classes for components that are utilized throughout the entire system. <style lang="scss" scoped> .specialPages { padding: 0 10px 30px 10px; } /deep/ .SelectorLabel { white-space: nowrap; al ...

What is the best way to eliminate the blue-box-fill when buttons are clicked?

Check out this screen recorded gif on my device showcasing the blue-box-fill I'm referring to: https://i.stack.imgur.com/ajr2y.gif I attempted the following solution: * { user-select: none; -webkit-user-select: none; /* Safari */ -khtml-user-s ...

Is there a way to turn off alerts from Aspx files for HTML and CSS?

Dealing with annoying warnings in my aspx files has been a constant struggle. The "CSS Value is not defined" message pops up when I reference CSS files from different projects, causing unnecessary frustration. Even more frustrating are the warnings about i ...

Attempting to transmit a text message to a PHP script using Ajax

Hey there! I'm facing a challenge while trying to send a string to a PHP file using AJAX. It seems like the http.send function is not working as expected, and I suspect there might be an issue in my code. (I'm fairly new to programming) mainlin ...

What is the best way to design an HTML table that features alternating colors for each row and column?

I recently came across this image showcasing a beautifully designed table: https://i.stack.imgur.com/6K63q.png The current HTML code I have applies colors to every even line, including the year columns and subcolumns. Is there a way to assign unique mixe ...

Bypass the Array.reduce method in JavaScript

I'm currently working on finding an elegant solution to a toy example pattern. The goal is to stop the reduce algorithm immediately and return 0 when an element with a value of 0 is encountered, without processing the rest of the elements. let factor ...

Troubleshooting problem with Z-Index conflict in Flash animation

I am facing an issue with two HTML divs - one containing a flash movie and the other simple text. I want to place the textual div on top of the flash movie div, but no matter how I set their positions in CSS or adjust their Z-Index values, the text keeps ...

Ways to implement functional component in ReactJs

I am currently working with Reactjs and utilizing the Nextjs framework. In my project, I am attempting to retrieve data from a database using Nextjs. However, I am encountering an error that states "TypeError: Cannot read property 'id' of undefin ...

Issues with sending emails through Nodemailer in a Next.js project using Typescript

I'm currently working on a personal project using Nodemailer along with Next.js and Typescript. This is my first time incorporating Nodemailer into my project, and I've encountered some issues while trying to make it work. I've been followin ...

Are there any available tools for automatically creating CSS classes based on your HTML code?

Out of pure curiosity, I am wondering if there is a program or script that can automatically generate a style sheet (with empty values) based on the structure of your HTML document. Essentially, it would extract the IDs and classes you have set in your H ...

Leverage JSON data in JavaScript

Having some trouble figuring out how to incorporate JSON values into my JS script. Any assistance would be greatly appreciated as I am still new to this! Below is the snippet of code where I need the values (lat and lon) to be inserted: var map; functio ...

Vue failing to update when a computed prop changes

As I work with the Vue composition API in one of my components, I encountered an issue where a component doesn't display the correct rendered value when a computed property changes. Strangely, when I directly pass the prop to the component's rend ...

Position the text to the right of the div or image and allow

My attempt to align the lorem ipsum sample text next to the image and div container by setting the float to right has not been successful. The text still remains below the image. Click here for visual reference Appreciate any help in advance. #outer { ...

How can I utilize match props in React JS with the Context API?

Currently working on a basic application that utilizes context API, fetch, and react hooks for all components except the context API component due to ongoing learning of hooks. The challenge lies in incorporating the match prop within the context API prov ...

jQuery Waypoints - multiple functions appear to be conflicting with one another

Greetings everyone on StackOverflow! I am facing an issue with jQuery Waypoints and couldn't find a solution for it. As a beginner in coding, please bear with me if the solution is simple. My website consists of five sections that appear like individ ...

Find your favorite artist on Spotify through the search function

Recently, I stumbled upon this intriguing demo showcasing how to search for an artist using the Spotify API. However, despite several attempts, I have been unable to make it function properly. Can anyone provide any tips or guidance on making this work suc ...

Using PHP header function to redirect to a specific form on an HTML page: A step-by-step guide

I have a dilemma in my web project. In the index.php file, there are two forms that utilize transitions to switch between pages (Login and Register). When attempting to register a new user in the backend, I check if the user already exists. If they do exis ...

How to add a subtle entrance animation to text (demonstration provided)

Apologies for the brevity, but I could really use some assistance with replicating an effect showcased on this particular website: My understanding is that a "fadeIn" can be achieved using jQuery, however, I am at a loss as to how to implement the 3D effe ...

I am interested in showcasing a card when it is hovered over

I am having trouble with a hover effect to display a hidden card. I have two div elements, one is labeled single-album and the other hide. I used the + selector to set the hide div to display none initially, but the hover effect is not working as expecte ...