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

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

Does the Mirage addon work effectively in the ember.js tutorial?

Following the ember.js tutorial, I'm facing a roadblock at this particular stage: (especially when implementing the Mirage add-on). I've made changes to the mirage/config.js file as advised but still unable to display the Mirage data. Despite ...

Using PHP variables in JavaScript is not compatible

Currently, I am facing an issue where PHP variables inside the javascript code are not being echoed. When I try to echo the variables outside of the javascript, everything works perfectly fine. After carefully reviewing my code multiple times, I still cann ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...

Modify the background of a Div element by selecting an alternate color palette

Here is my code that changes the background of a Div on select change from a dropdown. I believe there might be a more efficient way to achieve this. Can anyone provide recommendations? Thank you for taking a look. $(document).ready(function() { $(" ...

transform ajax data into an array structure

I need to convert the values retrieved from an AJAX call into an array so that I can access and format them accordingly. $(document).ready(function() { $('#documenter_nav > li a').click(function(){ var url = $(this).attr('data- ...

Is it possible to customize the appearance of the selected item in a select box? Can the selected value be displayed differently from the other options?

My current project involves working with the antd' select box. I have been trying to customize the content inside the Option which usually contains regular text by incorporating some JSX into it. The output currently looks like this: I have also crea ...

Choosing Only the Visible Element with CSS

Within my program, there exists a text element that appears in two distinct sections: section A and section B (in the form of a popup). My intention was to create one object using CSS that could be utilized in both areas. By doing so, I would be able to em ...

JavaScript Regular Expression Assistance Domain Snatcher

I am in the process of developing a JavaScript Regex and I am struggling to find the right pattern to match a specific domain. Let me provide an example for better understanding. I need a regex that can identify any domain that exclusively contains (text. ...

Troubleshooting issues with a Node.js application on Azure App Service

Seeking assistance with deploying my first Node.js app on Azure App Service. Despite following Microsoft's guides and tutorials, my app is not functioning as expected. Although I can see my project in the Azure portal, when I attempt to access it via ...

Custom view with spannable text functionality

Can a custom view be included in a spannable text? I've noticed various types of spannable objects in the android.text.style package, but I'm curious if it's possible to insert a custom view. Something like spanable.setSpan(CustomView, .. ...

Leveraging the power of nodejs functions within static HTML files in expressJs

Being a beginner in Javascript and Nodejs, I am uncertain about the best way to organize my project. I am currently working on creating a web interface for a C++ application using Nodejs and V8 to wrap a C++ API. My question is, can I utilize Express to se ...

The battle between nested flexbox heights and max-heights

Note: I am observing some unusual behavior on Chrome 72. FireFox 64 seems to be working fine! I am experiencing an issue with a nested flexbox. In the code snippet below, I have added an artificial XL height to .root.container in order to achieve the des ...

What is the process for deploying a next.js application with a custom express backend to a VPS or Heroku platform?

Does anyone have advice on deploying a next.js application with a custom express backend to either a VPS or Heroku? ...

When generating dynamic text boxes, a new area is always allocated for each new set of dynamic text boxes that are created

<html> <head> <script src="jquery-1.10.2.min.js"></script> <script> function AddingTextBoxes() { var NumOfText=$("#NumOfTextBoxes").val(); $('#NewlyCreatedSe ...

What is the best way to display a list of items in Vue JS while maintaining the

Looking to display my Vue.js list in reverse order using v-for without altering the original object. The default HTML list displays from top to bottom, but I want to append items from bottom to top on the DOM. Telegram web messages list achieves this wit ...

Vue: update data and trigger function upon completion of animation transformation, utilizing animation transformation completion listener

Check out this straightforward Vue example: https://codesandbox.io/s/sleepy-haze-cstnc2?file=/src/App.vue https://i.stack.imgur.com/zboCb.png Whenever I click on the square, it not only changes color but also expands to 200% of its original size with a 3 ...

What are the steps to achieve a smooth transition from a background-image to transparency?

Take a look at this related image: The goal is to replicate the design shown on the right side of the image. However, there's also a parent container with its own background image, as opposed to a solid color. Any guidance on how to achieve this? U ...

Is there a library available for generating QR codes on the server side and saving them directly to a database

My Goal: I am looking to create a functionality where, upon clicking "Generate QRCode," JavaScript will utilize the local machine's datetime to generate an md5 hash in the MMDDYYHHMMSS format. I then want this hash to be sent to the server to produce ...

Router failure resulted in an internal server error

When navigating to a page in my router, I make a REST API request to retrieve data from the server in the beforeEnter clause as shown below: beforeEnter: (to, form, next) => { getData().then( (response) => { ...