What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this.

function wiggle(){
  var parent = document.getElementById("wiggle");

  var string = parent.innerHTML;
  parent.innerHTML = "";
  string.split("");
  var i = 0, length = string.length;
  for (i; i < length; i++) {
      parent.innerHTML += "<span style='--n:"+ (100 * i - 10000 + 'ms') + ";'>" + string[i] + "</span>";
  }

}

wiggle()
#wiggle span{
  animation-delay: var(--n);
  animation: wave 2s linear var(--n) infinite forwards running;
  position: relative;
}

@keyframes wave{
  0% {top: 0px;}
  25% {top: -4px;}
  50% {top: 0px;}
  75% {top: 4px;}
  100% {top: 0px;}
}
<h1 id="wiggle">This text should wiggle...</h1>

<h2 id="wiggle">...while this text should not.</h2>

The current setup involves JavaScript splitting the ID of each letter into separate <span> tags, while CSS assigns animation delays and specifies the height of the animation waves. However, I aim to extend this animation to multiple headers on my page by targeting classes instead of IDs. Unfortunately, changing getElementById to getElementsByClassName, as well as modifying #wiggle to .wiggle, did not yield the desired outcome, and the animation no longer displays. Is there a way to modify the JavaScript to target classes without disrupting its functionality?

Answer №1

To prevent the wiggle effect, do not include the "wiggle" class.

const shake = (elementOrSelector) => {
  const element = typeof elementOrSelector === 'string'
    ? document.querySelector(elementOrSelector)
    : elementOrSelector;
  if (!element.classList.contains('shake')) {
    element.classList.add('shake'); // Alternatively, use a data attribute for control
  }
  const text = element.textContent;
  element.textContent = '';
  element.innerHTML = text.split('').reduce((html, c, i) =>
    (html + `<span style="--n:${10 * i - 10000}ms;">${c}</span>`), '');
};

const shakeAll = () => {
  document.querySelectorAll('.shake').forEach(shake);
}

shakeAll(); // Apply shake effect to all elements

shake('.shake-single'); // Manually trigger the shake effect
@keyframes wave {
  0%   { top:  0px; }
  25%  { top: -4px; }
  50%  { top:  0px; }
  75%  { top:  4px; }
  100% { top:  0px; }
}

.shake span {
  animation-delay: var(--n);
  animation: wave 2s linear var(--n) infinite forwards running;
  position: relative;
}
<h1 class="shake">This text will shake...</h1>

<h2>...while this text will remain still...</h2>

<h1 class="shake">...but this one will shake.</h1>

<h1 class="shake-single">Trigger manual shake effect...</h1>

If desired, consider adding a class to the span elements and updating your CSS styles to provide more flexibility and separation between the elements and their containers.

const shake = (elementOrSelector) => {
  const element = typeof elementOrSelector === 'string'
    ? document.querySelector(elementOrSelector)
    : elementOrSelector;
  const text = element.textContent;
  element.textContent = '';
  element.innerHTML = text.split('').reduce((html, c, i) =>
    (html + `<span class="shaker" style="--n:${10 * i - 10000}ms;">${c}</span>`), '');
};

const shakeAll = () => {
  document.querySelectorAll('.shake').forEach(shake);
}

shakeAll(); // Shake all elements

shake('.shake-single'); // Trigger the shake effect manually
@keyframes wave {
  0%   { top:  0px; }
  25%  { top: -4px; }
  50%  { top:  0px; }
  75%  { top:  4px; }
  100% { top:  0px; }
}

.shaker {
  animation-delay: var(--n);
  animation: wave 2s linear var(--n) infinite forwards running;
  position: relative;
}
<h1 class="shake">This text will shake...</h1>

<h2>...while this text will remain still...</h2>

<h1 class="shake">...but this one will shake.</h1>

<h1 class="shake-single">Trigger the shake effect manually...</h1>

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

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...

Modifying an onClick handler function within a react element located in a node module, which points to a function in a prop declared in the main Component file

I have successfully implemented the coreui CDataTable to display a table. return ( <CDataTable items={data} fields={fields} ... /> ) Everything is working smoothly, but I wanted to add an extra button in the header of the C ...

Retrieve information from the database upon clicking the submit button

My table is not getting data from the database when I click a button. I tried using this code but it returned an error. <div class="wrapper wrapper-content animated fadeInRight"> <div class="row"> <div class="col ...

Is there a way to align my green button beside the red button instead of below it?

I'm looking to rearrange the positioning of my green button on the screen. When I initially created the button, it ended up below my red button, but I want them to be displayed side by side. I haven't attempted any solutions because I am a beginn ...

Ways to avoid data looping in jQuery Ajax requests

This is in relation to the assignment of multiple users using the Select2 plugin, Ajax, and API. The situation involves a function that contains 2 Ajax calls with different URLs. Currently, there are pre-selected users stored in the database. The selection ...

Adding data to a URL using jQuery Ajax

I'm currently working on implementing Ajax with jQuery and I have a specific requirement to add data to the URL. Take a look at the code snippet below: var my_website= mysamplesite.com/viewData/"; function displayData(myData) { $.ajax({ t ...

What could be the reason for the status OVER_QUERY_LIMIT appearing before Status.OK in the Google Maps API response

Why does status OVER_QUERY_LIMIT appear before Status.OK in my code? Here is the code I am using: directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { var distance = Math.ceil(response. ...

Analyzing JavaScript code coverage through unit testing with Jenkins and SonarQube

We have successfully implemented Jenkins/SonarQube to enforce a requirement that any new code committed by developers must have at least 70% unit test code coverage for Java. However, when it comes to applying the same rule for JavaScript, we encountered s ...

Exploring the seamless integration of Material UI slider with chart js

Looking for guidance on syncing Material UI slider with chart js? I'm working on a line chart and hoping to have the x-axis value highlighted with tooltip as I slide the Material UI slider. ...

AngularJS - Determine the correct condition or make a choice from the available options

I'm having trouble figuring out how to save the option I select to a viewmodel. The ng-model should save whatever option I choose, and if nothing is selected, the value should default to "Select One." The available options are YES (true) / NO (false). ...

What is the method for retrieving a value from my Node.js module once it has been modified by an asynchronous function?

Apologies, but as a beginner developer, I'm struggling to see how this relates directly to the questions already mentioned. I have no understanding of ajax and I'm unsure how to adapt the solutions provided to my own situation. Currently, I&apos ...

The ejs file is failing to load the css file

I'm facing an issue where my layout.ejs file is not loading the style.css file. I've been searching endlessly for a solution, trying various fixes and meticulously checking for typos. Despite the correct path shown in the network tab when inspect ...

Understanding the sequence of operations in Javascript using setTimeout()

If I have the following code: function testA { setTimeout('testB()', 1000); doLong(); } function testB { doSomething(); } function doLong() { //takes a few seconds to do something } When I run testA(), what happens after 1000 mill ...

The npm start command is no longer functioning in Angular 5

When attempting to start angular 5 with npm, I encountered an error that reads: TypeError: callbacks[i] is not a function Can anyone shed some light on where this error might be coming from? It seemed to pop up out of the blue and I can't seem to ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

Exploring the Bounds of Mongodb's $within Query

I'm currently working on a geospatial query in mongodb using the $within operator. I have a collection entry with a location field containing: location: { bounds: { south_west: { lat: XX.XXXXXX, lng: XX.XXXXX }, north_east: { lat: XX.XXXXXX ...

What other option can be used in place of white-space:nowrap?

When using a textarea with the CSS property white-space:nowrap, it successfully removes spaces but adds a horizontal scrollbar to the text. I want to avoid the horizontal scrollbar while also preventing scrolling using arrow keys when using overflow-x:hi ...

Determine whether a component is linked to an event listener

If a <Form> component is called with a @cancel event listener attached to it, the cancel button that triggers this event should be visible. If no @cancel event is present, the cancel button should not be displayed. Is there a method to verify if a c ...

Excessive form inputs extend beyond the modal when utilizing Bootstrap 3

Having an issue loading a modal with Angular and populating it with a template. The main problem I'm facing is that the inputs are extending beyond the boundaries of the modal - attached below is a screenshot illustrating the problem: Below is the c ...

Building React Typescript Components with Froala Editor Plugins

Attempting to integrate a custom plugin into a Froala Editor within my React application using the package react-froala-wysiwyg. Following a tutorial on incorporating a custom popup/plugin found here. Encountering an issue due to TypeScript incompatibility ...