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

Is it possible to convert a DOM object into a JSON object for transfer?

Is there a way to send an entire row of a table to a php page via POST without using jQuery or having to loop through the object and rebuild it? When I tried using JSON.stringify(rowObject), I encountered an error, possibly due to the object being "cycli ...

What is the process for retrieving an HTML file dynamically and using it to populate a DIV with jQuery?

Can you explain how to carry out the following three steps: 1. Retrieve an HTML source from the server side 2. Utilize the retrieved source to generate a DIV element 3. Add the generated DIV element to the <body> element ...

Displaying dynamic text using radio buttons utilizing React

Currently, I am in the process of developing a multiple choice quiz where each question is presented with various options displayed as radio buttons. My main objective is to show specific text related to the option selected by the user when they make a ch ...

Experiencing difficulty receiving a full response from an ajax-php request displayed in a div

Having trouble getting a response in a div from an ajax request triggered by an onclick event in a form and a PHP page. Here's the code: <html> <head> <script language="javascript"> function commentRequest(counter) { new Ajax. ...

Tips for setting extra field values in the CKEditor image dialog during editing

One of my goals is to ensure that any images added in the ckeditor through the image dialog are responsive. To accomplish this: I have created a new option called 'srcset' in the advanced tab I removed the width and height properties from the ...

What are the best practices for utilizing pre-defined CSS classes in Vue.js libraries?

I don't have much experience with CSS, but I'm really eager to customize the appearance of my chart. The chart is generated by a vue.js library and comes with pre-defined CSS classes. However, I'm uncertain about how to access and modify the ...

Submitting a form using jQuery and processing the response

Can a form be submitted using jQuery without utilizing json, ajax, or other methods for handling the result? For example: <form id="loginform"> //some input fields and a submit button. </form> And then with jQuery: $("#loginform").sub ...

Create a JavaScript function that continues to execute even after a button has been clicked

Although it may seem like simple logic, I am currently unable to log in. Imagine I have a function called mytimer() stored in a common file that is linked to every HTML page. mytimer(){...........................}; Now, at some point on another page, whe ...

Using jQuery to Retrieve Accurate User Identification - Making AJAX Requests

Currently, I am facing a bit of a dilemma. I have implemented 2 jQuery scripts to handle updating a simple database row based on user ID and session. This functionality allows users to send a "Gift" that adds value to their database row column "bonus". Wh ...

Tips for creating multiple diagonal lines with CSS and HTML

Is there a way to create multiple diagonal lines within a rectangle using CSS and HTML from the start? I am interested in incorporating diagonal lines at the onset of the rectangle. Here is an example code that displays the rectangle: <div className={ ...

Obtain an array containing only unique values from a combination of arrays

Is there a simple way or plugin that can help me combine values from multiple arrays into one new array without duplicates? var x = { "12": [3, 4], "13": [3], "14": [1, 4] }; The resulting array should only contain unique values: [1, 3, 4]; ...

Using Bootstrap 4: How to maximize the width of a span element placed near a label

I need to adjust the width of a span next to its label in my project. My goal is to show multiple groups {label / data} on the same line. To achieve this, I divided the row into 4 columns and tried to set a specific width for a span. However, no matter wh ...

Leveraging Global SCSS Variables in Next.JS with SASS

In my Next.js Application, I have a global CSS file named main.scss imported in the pages/_app.js file. _app.js import '../global-styles/main.scss' export default function MyApp({ Component, pageProps }) { return <Component {...pageProps} ...

Trouble with setting HTML table width

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <table border="1" width="100%"> <tr> <td>bbbbbbbbbbbbbbbbbbbbbbbbbbb ...

A beginner's guide to importing modules in Node.js

Whenever I attempt to import into my nodejs file, I consistently encounter the error message stating "cannot import outside a module." I have experimented with various solutions found on StackOverFlow, such as including "type":"module" ...

Is there a way to link code and unit testing directly to npm test?

Is there a method to conduct unit testing in real-time on my server without having to create temporary files? I am looking for a way to supply both the code to be tested and the corresponding unit test to npm test. The information provided in the npm test ...

When attempting to showcase array information in React, there seems to be an issue with the output

After printing console.log(response.data), the following output is displayed in the console. https://i.sstatic.net/LLmDG.png A hook was created as follows: const [result,setResult] = useState([]); The API output was then assigned to the hook with: setRe ...

Mat-SideNav in Angular Material is not toggled by default

<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>{{applicationN ...

Retrieving Data using Map in ReactJS

I'm in the process of creating a web app and I have an array of data with URLs in each element. I'm struggling to figure out how to fetch data from these mapped URLs. useEffect(() => { axios .get(`someurl`) .then((response) =& ...

Organize the array by property name and include a tally for each group

My current data structure looks like this: var data = [ { MainHeader: Header1, SubHeader: 'one'}, { MainHeader: Header1, SubHeader: 'two'}, { MainHeader: Header2, SubHeader: 'three'}, { MainHeader: Header2, SubHea ...