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

What is causing the local storage to not persist after refreshing the page?

Even after a browser refresh, the button text 'completed' should remain intact depending on whether the variable item is true (after the button click). I have experimented with Chrome and believe the issue is not related to the browser. <temp ...

Is there a way to simulate pressing a keyboard button using jQuery?

Below is the code snippet: $("input").on({ keydown: function(ev) { if (ev.which === 27){ // esc button backspace_emolator(); } else if (ev.which === 8){ // backspace button console.log('backspace button ...

What is the method for retrieving the currently selected value in a MultiColumnComboBox within Kendo for Angular?

Check out this live example created by the official Telerik team: I need to extract the id (referenced in contacts.ts) of the currently selected employee when clicking on them. How can I access this information to use in another function? ...

When I attempt to run several promises simultaneously with Promise.All, I encounter an error

My code contains a series of promises, but they are not being executed as expected. Although the sequence is correct and functional, I have found that I need to utilize Promise.all in order for it to work properly. dataObj[0].pushScreen.map(item => { ...

What is the process for transforming a nested dictionary in JSON into a nested array in AngularJS?

I am looking to create a form that can extract field values from existing JSON data. The JSON I have is nested with dictionary structures, but I would like to convert them into arrays. Is there a way to write a recursive function that can retrieve the key ...

Contrast between the structure of asp.net button and hyperlinks

I want to transfer the styles of a hyperlink in regular html to an Asp.net button. However, I encountered a strange background issue that is disrupting the appearance of the buttons. Hyperlink: Asp.net Button How can I remove the outline that appears o ...

Navigating through a predetermined list of HTML pages with next and previous options

Hey there, I'm in a bit of a quandary at the moment. I've been searching on Google for quite some time now, but unfortunately, I can't seem to find what I'm looking for. Hopefully, you guys can lend me a hand. What I'm trying to d ...

Setting up Material UI Icons in your React js project

I've been having trouble installing the Material UI Icons package with these commands: npm install @material-ui/icons npm install @material-ui/icons --force npm i @mui/icons-material @mui/material Error messages keep popping up and I can't see ...

Is the Piecemaker flash slider being obstructed by its container?

I am currently integrating the Piecemaker flash slider into my new project for the very first time. Unfortunately, I'm facing an issue where the animation is getting cut off by the dimensions of its container. I've been struggling to figure out h ...

Please follow the format of "M d, yy" when entering the date

I need to change the format of newDate from Tue Dec 24 2013 00:00:00 GMT+0530 to Dec 24, 2013 var dateString = 'Dec 17, 2013'; // date string var actualDate = new Date(dateString); // convert to actual date var newDate = new Date(actualDate.getF ...

The first item in Swiper is incorrectly displayed after the initial cycle, even though the data is accurate

Currently, I am incorporating the slider functionality in Vue using the Swiper framework. Although everything seems to be functioning properly, there is a minor issue that arises when filtering the data and completing the first cycle after scrolling. The f ...

Selecting items with checkboxes in a Bootstrap dropdown menu

As I work on customizing a bootstrap dropdown with checkboxes, my goal is to have the label name written on the input dropdown in between ';' whenever a checkbox from the dropdown is selected. This will create a similar result as shown in the upl ...

Using QuerySelector with Angular Directive will throw an error as it is not a recognized

When creating a directive that integrates a jQuery carousel, I want to hide it at the beginning until it is fully ready. Here's the directive code snippet: return { restrict: 'E', replace: true, scope: true, templateUrl: ...

Establishing the default selection and deactivating the notification

I've been struggling for a while to make this function properly. My knowledge of jquery and javascript is limited, so I'm facing some challenges. What I'm aiming to do is to have a default option selected from the drop-down menu when the but ...

Vue Dev Tools is not updating data in Ionic Vue 3

There seems to be an issue with the updating of Reactive and Ref data in Vue Dev Tools when changes are made in an input field bound with v-model within a form. The updated data is only visible when I interact with another component and then return to the ...

How to utilize jQuery to eliminate HTML onchange code

This block of code features an HTML onchange attribute as well as the use of jQuery's change event on an input text. I want only the jQuery change event to take precedence. I have attempted to use both unbind and off without success. Can someone prov ...

Refreshing a div's content with a single click to update the page

I'm experimenting with elements above my head and striving to absorb new knowledge. In my admin page, I use jQuery to reveal a hidden div that displays another page within it. Here's how I achieve this: $(document).ready(function(){ $("a#fad ...

What is the proper way to execute a JavaScript function within a JavaScript file from an HTML file?

I have the following content in an HTML file: <!DOCTYPE html> <!-- --> <html> <head> <script src="java_script.js"></script> <link rel="stylesheet" type="text/css" href="carousel.css"> & ...

Tags that adhere to W3C compliance for struts

I'm facing an issue with a web page created using struts tag libraries. When attempting to validate the page on w3c.org, all the struts tags are showing up as undefined. For example, <html:button> appears as undefined. The DOCTYPE I used is: &l ...

CSS Navigation Bar Fails to Function Properly on Mobile Devices

Check out the plunkr I have created by visiting: http://plnkr.co/edit/gqtFoQ4x2ONnn1BfRmI9?p=preview The menu on this plunkr functions correctly on a desktop or laptop, but it doesn't display properly on a mobile device. I suspect that the issue may ...