What could be causing the issue of CSS animation not functioning properly when used in conjunction with a

I am working on creating a switch button with CSS and JavaScript that needs an animation when toggling or clicked. The only issue I am facing is related to the animation.
I am wondering if there might be any problem with the positioning (relative, absolute)? Although I know that the css property left can be animated, I am not sure why it's not working in this case.

(function (){
  
  let 
  
      btn = document.querySelector ('.input-switch'),
      container = document.querySelector ('.input-switch-container'),
      checkbox = container.querySelector ('input[type="checkbox"]');
  
  btn.addEventListener ('click', function (){  
    container.classList.toggle('active');
    checkbox.checked ?  checkbox.checked = false :  checkbox.checked = true;
  });
  
}())
*,
*::before,
*::after{
  box-sizing: border-box;
}

.input-switch{
  border-radius: .25rem;
  width: 112px;
  border: 1px solid #ddd;
  overflow: hidden;
  cursor: pointer;
  user-select: none;
}

.input-switch-container {
  position: relative;
  display: flex;
  transition: all 1.3s linear;
}

.input-switch-container.active{
  left: -56px;
}

.input-switch-on,  
.input-switch-off,
.input-switch-empty{
  padding: .25rem 1rem;
  line-height: 1.5;
  flex: 0 0 50%; 
}

.input-switch-on{
  background-color: #007bff;
  color: #fff;
}

.input-switch-off{
  background-color: #f1f1f1;
}

.input-switch-empty{
  background-color: #fff;
}

.input-switch input[type="checkbox"]{
  opacity: 0;
}
<div class="input-switch">
  <div class="input-switch-container">
    <span class="input-switch-on">ON</span>
    <span class="input-switch-empty"></span>
    <span class="input-switch-off">OFF</span>
    <input type="checkbox" />
  </div>
</div>

Answer №1

To begin with, assign an initial value of left to .input-switch-container.

(function (){
  
  let 
  
      btn = document.querySelector ('.input-switch'),
      container = document.querySelector ('.input-switch-container'),
      checkbox = container.querySelector ('input[type="checkbox"]');
  
  btn.addEventListener ('click', function (){  
    container.classList.toggle('active');
    checkbox.checked ?  checkbox.checked = false :  checkbox.checked = true;
  });
  
}())
*,
*::before,
*::after{
  box-sizing: border-box;
}

.input-switch{
  border-radius: .25rem;
  width: 112px;
  border: 1px solid #ddd;
  overflow: hidden;
  cursor: pointer;
  user-select: none;
}

.input-switch-container {
  position: relative;
  display: flex;
  transition: all 1.3s linear;
  left: 0;
}

.input-switch-container.active{
  left: -56px;
}

.input-switch-on,  
.input-switch-off,
.input-switch-empty{
  padding: .25rem 1rem;
  line-height: 1.5;
  flex: 0 0 50%; 
}

.input-switch-on{
  background-color: #007bff;
  color: #fff;
}

.input-switch-off{
  background-color: #f1f1f1;
}

.input-switch-empty{
  background-color: #fff;
}

.input-switch input[type="checkbox"]{
  opacity: 0;
}
<div class="input-switch">
  <div class="input-switch-container">
    <span class="input-switch-on">ON</span>
    <span class="input-switch-empty"></span>
    <span class="input-switch-off">OFF</span>
    <input type="checkbox" />
  </div>
</div>

If you rearrange the HTML and make some CSS adjustments, you can achieve the same outcome without needing any javascript.

The crucial element in the CSS code is this:

.input-switch input[type="checkbox"]:checked + .input-switch-container {
  left: -56px;
}

*,
*::before,
*::after{
  box-sizing: border-box;
}

.input-switch{
  border-radius: .25rem;
  width: 112px;
  border: 1px solid #ddd;
  overflow: hidden;
  cursor: pointer;
  user-select: none;
  display: block;
}

.input-switch-container {
  position: relative;
  display: flex;
  transition: all .3s ease;
  left: 0;
}

.input-switch-on,  
.input-switch-off,
.input-switch-empty{
  padding: .25rem 1rem;
  line-height: 1.5;
  flex: 0 0 50%; 
}

.input-switch-on{
  background-color: #007bff;
  color: #fff;
}

.input-switch-off{
  background-color: #f1f1f1;
}

.input-switch-empty{
  background-color: #fff;
}

.input-switch input[type="checkbox"] {
  display: none;
}

.input-switch input[type="checkbox"]:checked + .input-switch-container {
  left: -56px;
}
<label class="input-switch">
  <input type="checkbox" />
  <div class="input-switch-container">
    <span class="input-switch-on">ON</span>
    <span class="input-switch-empty"></span>
    <span class="input-switch-off">OFF</span>
  </div>
</label>

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 are some strategies to reduce the frequency of API calls even when a webpage is reloaded?

Imagine I'm utilizing a complimentary API service that has a restriction of c calls per m minutes. My website consists of a simple HTML file with some JavaScript code like the one below: $(function () { //some code function getSomething() { ...

Deliver the event target within the data-bind click HTML

I am having trouble sending the event target when passing parameters in data-bind. <button class="tablinks" data-bind="click:$root.notify.bind(this, 1, 'foo');" id="defaultOpen">PRINCIPAL</button> self.notify = function (str, id, e) ...

Unable to apply CSS modifications to child elements in AngularJS

angular.element($document[0].querySelector("table > tbody > tr")).mouseover().css("background-color", "red"); <table> <thead> <tr> <th>Name</th> < ...

Preparing user context prior to executing controllers within AngularJS

I recently created an AngularJS application and integrated a REST API to fetch resources for the app. As part of the authentication process, I store the user's access token in a cookie. When the user reloads the page, I need to retrieve user informati ...

Within Blade, Laravel and Vue components are able to communicate by sharing data from one component to another

Is it possible to achieve this task? Here is the scenario: I have a left navbar displaying membership status (active/inactive). Once the payment gateway receives the payment, a webhook is triggered via Paddle(Laravel Paddle API). During the webhook proc ...

Creating an angular controller in a template based on certain conditions

When working with Angular.js, I'm attempting the following: index.html <div class="data-tabs-sms-scroll" ng-show="question.type == 'open'" ng-controller="AudioMessagesCtrl" ng-include="'/templates/audioMessages.html' ...

How can I show the content of a variable in Next.js without displaying any HTML tags?

For instance, I have the description variable set up like this in NextJS: description={storeDetail?.translation?.description} When outputting the description, it shows me <p>Tenis</p>. However, I would prefer to display just "Tenis" without th ...

No elements can be located within the iframe as per Cypress's search

I've been attempting to access elements within an iframe using the guidance provided in this article here, but I'm facing an issue where Cypress is unable to locate anything within the iframe. Below is a snippet of my test code: describe('s ...

Using AJAX to load multiple pages asynchronously

Recently, I put together a website using the following script: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script> function loadpage(page) { document.getElementById( ...

Vue 3 throws an error stating: "An uncaught DOMException occurred because the string contains an invalid character."

Exploring the capabilities of vue.js on a basic website. The setup consists of a single index.html file and all JavaScript is housed in an index.js file. The website is a work in progress, but there are no blockers preventing the JavaScript functionality ...

Populate vue-multiselect with links from the router

Is there a way to populate the vue-multiselect dropdown with <router-link> options? Typically, router links are defined declaratively in the <template>, but vue-multiselect relies on binding an array of options. Any suggestions on how to approa ...

Assist with JavaScript Programming

Can someone assist me in creating functionality for the "Show Picture" button to toggle the visibility of the picture when clicked? I've been trying to achieve this using an If/Else statement for a school project but have been struggling with it. Any ...

Adjusting the height property to zero in the absence of an element

I'm currently working on creating a timeline for changeLogs and populating it with data from an AngularJS controller. The issue I'm facing is that the height of the timeline "Line" is set to 6px. This means that even when there is no data in the ...

Maintaining consistent row height in bootstrap when displaying or hiding a button

I'm currently working on a project utilizing AngularJS and Bootstrap to create a dynamic form. My goal is to have an 'edit' button display when a user hovers over a specific row of the form. However, I'm facing an issue where the row&ap ...

Iterate through JSON and dynamically populate data

My goal is to dynamically populate content by iterating through JSON data using jQuery. First, an Ajax request is made Then the data is looped through to create HTML tags dynamically A div container with the class "product-wrapper" is created for each J ...

Toggle divs by using a checkbox (Vue.js)

On my authentication page, I have implemented a checkbox that I want to use to toggle between Sign Up and Sign In forms. When the checkbox is clicked, it should display the Sign Up form, and when it's unchecked, it should show the Sign In form. I fou ...

Is it possible for me to hand over control to a child process and retrieve the result in Node.js?

Recently, I encountered an issue where multiple simultaneous GET requests to my Node.js server caused it to become overwhelmed and unresponsive, leading to timeouts for clients (503, service unavailable). Upon thorough performance analysis, I discovered t ...

Three.js - Exploring the Significance of "THREE" within the THREE.scene Framework

Just starting out in JavaScript and experimenting with animations using three.js library. I'm trying to grasp the meaning behind: const scene = new THREE.Scene(); Why is the "THREE" necessary in THREE.Scene? Could we not simply write const scene = n ...

Methods for validating ajax response with Jasmine

I'm a newbie when it comes to jasmine and I'm trying to figure out how to verify if a specific node is present in the ajax response. Currently, I'm using grunt to run jasmine from the command line and have successfully tested if a function i ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...