Performing a dynamic animation by toggling the class of an element with "classList.toggle" in JavaScript

I have been attempting to incorporate a fade animation using CSS when altering the class of the input and label elements within a form by utilizing the classList.toggle method in JavaScript. I'm puzzled as to why my code isn't producing the desired animation effect; could there be an error in my implementation?

const checkBox = document.querySelector('#checkBox');
const label = document.querySelector('#label');

function check() {
  if (checkBox.checked) {
    label.innerHTML = '<-<span>Un</span>Checked :)'
  }

  if (!checkBox.checked) {
    label.innerHTML = '<-UnChecked :('
  }
}

checkBox.addEventListener('click', check);
checkBox.click();

setInterval(() => {

  checkBox.click();
  label.classList.toggle('animation');
  checkBox.classList.toggle('animation');
  label.classList.toggle('animation2');
  checkBox.classList.toggle('animation2');

  setTimeout(() => {
    checkBox.click()
    label.classList.toggle('animation');
    checkBox.classList.toggle('animation');
    label.classList.toggle('animation2');
    checkBox.classList.toggle('animation2');

  }, 2000);
}, 4000);
* {
  font-family: 'Cartograph CF';
}

#checkBox {
  height: 20px;
  width: 20px;
  margin-right: 10px;
}

form {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 50px;
  font-size: 30px;
}

label {
  user-select: none;
}

.animation {
  animation: fade .3s ease-in-out forwards;
  opacity: 0;
}

.animation2 {
  animation: fade .3s ease-in-out forwards;
  opacity: 0;
}

span {
  opacity: 0;
}

@keyframes fade {
  form {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <form>

    <input type="checkbox" id="checkBox" class="animation">
    <label for="checkBox" id="label" class="animation"><-UnChecked :(</label>

  </form>
</body>

</html>

Answer №1

To achieve seamless animation transitions, it is recommended to utilize the css transition property as opposed to the more complex animation property. One solution for smoothly changing text is to create two elements within the label and alternate between displaying them.

const checkBox = document.querySelector('#checkBox');
const visible = document.querySelector('.visible');
const hidden = document.querySelector('.hidden');

function verify() {
  if (checkBox.checked) {
    checkBox.classList.remove('animation');
    visible.classList.add('animation');
    hidden.classList.remove('animation');
  }

  if (!checkBox.checked) {
    checkBox.classList.add('animation');
    visible.classList.remove('animation');
    hidden.classList.add('animation');
  }
}

checkBox.addEventListener('click', verify);
checkBox.click();

setInterval(() => {
  checkBox.checked = false;
  checkBox.classList.remove('animation');
  visible.classList.remove('animation');
  hidden.classList.add('animation');

  setTimeout(() => {
    checkBox.checked = true;
    checkBox.classList.add('animation');
    visible.classList.add('animation');
    hidden.classList.remove('animation');
  }, 2000);
}, 4000);
* {
  font-family: 'Cartograph CF';
}

#checkBox {
  height: 20px;
  width: 20px;
  margin-right: 10px;
  opacity: 1;
  transition: opacity 0.5s ease-in-out;
}

form {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 50px;
  font-size: 30px;
}

label {
  width: 250px;
  height: 30px;
  user-select: none;
  position: relative;
}

.animation {
  opacity: 0;
}

span {
  position: absolute;
  opacity: 1;
  transition: opacity 0.5s ease-in-out;
}
<form>
  <input type="checkbox" id="checkBox" class="animation" />
  <label for="checkBox" id="label"><span class="visible"><-UnChecked :(</span>
        <span class="hidden animation"><- Checked :)</span></label
      >
    </form>

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

Model in Sequelize does not get updated

I have a basic user model with two simple relationships: export const Password = sequelize.define("password", { hash: { type: DataTypes.STRING, allowNull: false, }, salt: { type: DataTypes.STRING, allow ...

When scrolling, the text or logo inside the navbar seems to dance with a slight wiggling or

I recently implemented a code to create a logo animation inside my navigation bar that expands and contracts as I scroll, inspired by the functionality of the Wall Street Journal website. However, this implementation has caused some unintended side effects ...

Exploring the Benefits of Combining Vue.js with Laravel

Being a newcomer to Vue, I decided to try it out in a recent project and quickly understood why it's so popular. Everything was running smoothly until I tested it in IE, where nothing seemed to work at all. Encountering errors like Object doesn' ...

What is the best method for eliminating tiny spaces between images that are aligned horizontally?

Check out this link for more details: . I am looking to eliminate the slim vertical gaps between the images in html5 without resorting to using the table cellpadding="0" cellspacing="0". Any ideas on how to achieve this? ...

typescript is failing to update CSSRule with the newly assigned background-color value

I am currently working on dynamically changing the CSS style (specifically background-color) for certain text on a webpage. To achieve this, I have been attempting to modify CSSRule by accessing the desired CSSRule based on selectedText. Here is the code s ...

Is there a term similar to "Rise above the Rest" in the world of Web Development?

Hey, I've encountered a new issue right now. Currently, I have two elements that are fixed to the top and bottom of the page. However, the elements in between them are overlapping the top element. Even though I tried keeping both elements fixed, th ...

The ajv-based middy validator does not adhere to the specified date and time format

When it comes to validation, I rely on middy as my go-to package, which is powered by ajv. Below is an example of how I set up the JSON schema: serviceDate: { type: 'string', format: 'date-time' }, The structure o ...

Plugin for jQuery that smoothly transitions colors between different classes

After searching through numerous jQuery color plugins, I have yet to discover one that allows for animating between CSS class declarations. For instance, creating a seamless transition from .class1 to .class2: .class1 { background-color: #000000 } .class ...

How can I turn off warnings for angular-translation?

A series of translation related warnings are appearing in the browser console, and I am looking to suppress or disable all of these warnings to prevent them from being shown to the user. Warnings: Translation for Department doesn't exist a.(anonymous ...

Adding HTML and scripts to a page using PHP and JS

Currently, I am utilizing an ajax call to append a MVC partial view containing style sheets and script files to my php page. Unfortunately, it seems that the <script> tags are not being appended. After checking my HTTP request on the network, I can ...

Execute the validation directive using the digest cycle

This particular directive is designed to determine whether a given value exists within the associated datalist or not. It functions flawlessly when I input text into the field, but it fails to work properly if the datalist undergoes changes as a result o ...

Update JSON values using JavaScript or jQuery

In the code snippet provided, there is an issue where nameElem.data('index') does not change, causing it to always display element 1 in the list. I attempted to change the json value with cardInfo[i].data.index = index;, but that did not solve th ...

The app in NextJs encounters layout issues on all pages due to a break in

I've developed a NextJs application using npx create-next-app and attempted to implement my own custom layout. However, this resulted in breaking the app unexpectedly without any clear reason. The project structure includes: components -> Footer.j ...

Tips for invoking a JavaScript function within an iframe

I'm looking to add an iframe to my HTML document, but I also need to pass a variable from a JavaScript function that is located on the same page (which retrieves cookie values). <script type=text/JavaScript> var generateLinkerUrl = function(url ...

Guide on updating individual rows in Google App Script using data from a different sheet

I am trying to create a script that will pull a value from column[3] in the ZONE sheet to the active sheet, specifically in column 56 of the job sheet when the zonelist value matches the zone value in different sheets. The script should check the range fro ...

Options for HTML technologies in an application designed for managing enterprise metadata

Challenge We are facing the decision of determining which technologies to adopt as we transition from a rich client Silverlight application to an HTML-based client that can accommodate a metadata driven approach. Situation Our enterprise has been using ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...

Dealing with the 'routes not found' error in a Node.js Express application (troubleshooting)

Attempting to address potential missing router errors in my app.js or router file has been a challenge for me. (various solutions found on Stack Overflow have not provided the correct resolution) The current state of my app.js or router files is functiona ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

Using JavaScript, extract the most recent 10 minutes worth of UNIX timestamps from a lengthy array

I am working with an array that contains multiple UNIX timestamps and I need to retrieve the timestamps from the last 10 minutes. Specifically, I only require the count of these timestamps, possibly for a Bot protection system. Would it be best to use ...