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

What is the reason for the immediate application of the set function in a useState hook within asynchronous functions?

While working with multiple set functions of a useState hook, I noticed different behaviors when calling them in sync and async functions. function Test() { console.log('app rendering starts.'); const [a, setA] = useState(1); const [b ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

Using React with Typescript: What is the best way to implement useMemo for managing a checkbox value?

I am currently developing a to-do list project using React and Typescript. At the moment, I have successfully implemented the functionality to add new to-do items via a form and delete them individually. Each item includes a checkbox with a boolean value. ...

Issues with LocalStrategy not executing in passport authentication

I am currently facing an issue with authenticating using Passport and LocalStrategy. It seems like the strategy is not being called and when I log the user object in passport.authenticate, it returns "false". Below is my client-side code: logIn = () =& ...

One can only iterate through the type 'HTMLCollection' by utilizing the '--downlevelIteration' flag or setting a '--target' of 'es2015' or above

I'm currently working on developing a loader for my static grid. I've incorporated the react-shimmer-skeleton package source code, but I'm encountering issues with eslint in strict mode. You can find the respective repository file by followi ...

Generate - Create 2 different versions of the web application

Currently, I am in the process of learning Grunt and exploring ways to generate 2 variations of an application with different configuration settings. My goal is to have one version where a boolean in a specific .js file is set to false, and another versio ...

Once a session is established within a route, it cannot be accessed or utilized in any other routes within the

I am currently in the process of setting up sessions for my node.js app. To achieve this, I am utilizing modules such as "express", "express-session", and "express-mysql-session" to store the sessions in a database on my server. While my code works perfect ...

The argument 'TabsCtrl1' is throwing an error as it is not recognized as a valid function and is showing as

I have encountered a problem with my controller, and I am seeing the following error message: Error: [ng:areq] Argument 'TabsCtrl1' is not a function, got undefined http://errors.angularjs.org/1.3.0-beta.11/ng/areq?p0=TabsCtrl1&p1=not%20a%20 ...

Tips for filtering data using an array within an object containing arrays

Below is the provided information: userRoom = ['rm1']; data = [{ name: 'building 1', building: [{ room: 'rm1', name: 'Room 1' },{ room: 'rm2', name: ' ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

Tips for reconstructing a path in Raphael JS

I am encountering a unique issue with my implementation of Raphael JS. Currently, I am working on drawing a donut element and seeking advice similar to the content found in this helpful link How to achieve 'donut holes' with paths in Raphael) var ...

jQuery's find method returns a null value

During my Ajax POST request, I encountered an issue where I wanted to replace the current div with the one received from a successful Ajax call: var dom; var target; $.ajax({ type: "POST", url: "http://127.0.0.1/participants", data: "actio ...

Using AngularJS to bind radio buttons to ng-model

Here is a snippet of my HTML code where I attempted to bind the "formFriendsAll" scope to the ng-model. <form ng-submit="submitForm()" > <div class="col-sm-3"> <div class="form-group"> <label>Which Persons to show?< ...

How to Eliminate the Border on the Final Item within a React List

Hi everyone, I need help with removing the border of the last item in an unordered list when the list reaches a certain size. I initially tried this: document.querySelector('.employee-list-item:last-child').style.border = "none"; However, I enc ...

Using the transform property with the scale function causes elements positioned in the bottom right corner to vanish

Issue specific to Google Chrome and Windows 10 I'm currently working on a flipbook that adjusts content size using transform:scale() based on the user's screen size. There is also a zoom feature that allows users to adjust the scale factor. I ha ...

Tips for incorporating HTML elements into XML emails

I'm facing an issue with my email template where the body of the email is being pulled as a String, resulting in raw html appearing in the email. Does anyone know how to insert an html tag into the body of an XML email using a String? <body> ...

Tips on avoiding the accumulation of event handlers when dealing with click events triggered by the document selector in jQuery

I am currently working on a project that involves using AJAX to load various pieces of HTML code. This is done in order to properly position dynamic buttons within each portion of the HTML content. In my case, I need to trigger click events on the document ...

Seamlessly transition between various states within a React component for a fluid user experience

I'm currently working on a simple component structured like this: var component = React.createClass({ render: function(){ if (this.props.isCollapsed){ return this.renderCollapsed(); } return this.renderActive() }, ren ...

Leveraging web workers for asynchronous API calls

Trying to find an efficient method for utilizing web workers to handle api calls, my current approach involves the following on the client side: - worker-client.js export const workerFetch = (method = "get", url = "/", data = {}) => new Promise((res ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...