What is the technique for moving a slider-like checkbox slider to one of its labels when they are clicked on?

Is there a way to make the switch slider move to the word the user clicked on (medium or large)? I'm not sure if I can track the movement of the switch slider with JavaScript or if it's possible to do with CSS. Right now, I have only created a simple toggle switcher with changing color. The issue is that the slider has been heavily customized with :before, :checked, input, and so on, so I don't even know where to start to make it happen.

.slider.round {
    border-radius: 34px;
  }
  
.slider.round:before {
    border-radius: 50%;
}

.row-inputs-radio {
    display: flex;
    justify-content: space-between;
}

.item-size {
    margin-left: 10px;
}

.item-size-eg {
    font-size: 15px;
    color: rgb(155, 154, 154);
}

.continue-btn button {
    outline: none;
}

.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 10px;
    margin-top: 15px;
  }
  
  .switch input { 
    opacity: 0;
    width: 0;
    height: 0;
  }
  
  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: -74px;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
    width: 187px;
  }
  
  .slider:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 4px;
    bottom: -3px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
    border: 1px solid grey;
  }
  
  input:checked + .slider {
    background-color: #13985C;
  }
  
  input:focus + .slider {
    box-shadow: 0 0 1px #2196F3;
  }
  
input:checked + .slider:before {
    -webkit-transform: translateX(120px);
    -ms-transform: translateX(120px);
    transform: translateX(162px);
}
<div class="column-input">
          <div class="row-inputs row-inputs-radio">
            <div class="row-input">
              <div class="item-size"><bold>Medium</bold></div>           
            </div>
            <div class="row-input">
              <label class="switch">
                <input type="checkbox" checked />
                <span class="slider round"></span>
              </label>
            </div>
            <div class="row-input">
              <div class="item-size"><bold>Large</bold></div>
            </div>
          </div>

Answer №1

Here is a breakdown of the steps:

  • Identify the elements with classes medium, large, and input
  • Attach event listeners for the onclick event to these elements for toggling
  • Update the CSS to include cursor: pointer to indicate these elements are clickable

var medium = document.querySelector('.medium'),
    large = document.querySelector('.large'),
    slider = document.querySelector('.switch input');;

medium.onclick = function() {
  slider.checked = false;
}
large.onclick = function() {
  slider.checked = true;
}
.medium, .large {
  cursor: pointer;
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}

.row-inputs-radio {
  display: flex;
  justify-content: space-between;
}

.item-size {
  margin-left: 10px;
}

.item-size-eg {
  font-size: 15px;
  color: rgb(155, 154, 154);
}

.continue-btn button {
  outline: none;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 10px;
  margin-top: 15px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: -74px;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
  width: 187px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 16px;
  width: 16px;
  left: 4px;
  bottom: -3px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
  border: 1px solid grey;
}

input:checked+.slider {
  background-color: #13985C;
}

input:focus+.slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
  -webkit-transform: translateX(120px);
  -ms-transform: translateX(120px);
  transform: translateX(162px);
}
<div class="column-input">
  <div class="row-inputs row-inputs-radio">
    <div class="row-input">
      <div class="item-size medium">
        <bold>Medium</bold>
      </div>
    </div>
    <div class="row-input">
      <label class="switch">
                <input type="checkbox" checked />
                <span class="slider round"></span>
              </label>
    </div>
    <div class="row-input">
      <div class="item-size large">
        <bold>Large</bold>
      </div>
    </div>
  </div>

Answer №2

Implementing Event Listeners with addEventListener()

To achieve the desired behavior, we can add event listeners to the labels to toggle the checkbox on click. Using event delegation, we only need to add a single event listener to the parent element.

We can implement a boolean value to determine if the clicked label is the "on" label that should check the checkbox. This boolean can directly set the value of the .checked attribute. Here's a simple pseudo-code representation:

  • Check if the label is the "on" label, then check the checkbox
  • If the label is not the "on" label, do not check the checkbox

We can identify the "on" label by checking if the .row-input div it belongs to is the last one in the list.

Accessibility Note: Simply adding a click listener to a non-clickable element does not make it accessible. To make an element accessible for click actions, one must:

  • Add appropriate listeners (click, key, etc.)
  • Ensure ARIA conformity for semantic meaning

While creating custom elements is possible, it involves substantial work. It is advisable to stick to the existing HTML specifications unless there's a specific need for custom elements.

Below is a snippet demonstrating the implementation:
Note: The code supports multiple .column-input elements.

Here is an example of the HTML and CSS code:

Answer №3

My demonstration does not involve assigning a unique class to each individual component. Instead, I utilized the forEach() method.

let select = document.querySelectorAll('.row-input .item-size');
let checked_pos = document.querySelector('.row-input .switch input[type="checkbox"]');

Array.from(select).forEach(function(selectCurrent, index) {
  selectCurrent.onclick = function() {
    if (index == 0) {
      checked_pos.checked = false;
    }
    if (index == 1) {
      checked_pos.checked = true;
    }
  }
});
.slider.round {
    border-radius: 34px;
  }
  
.slider.round:before {
    border-radius: 50%;
}

.row-inputs-radio {
    display: flex;
    justify-content: space-between;
}

.item-size {
    margin-left: 10px;
}

.item-size-eg {
    font-size: 15px;
    color: rgb(155, 154, 154);
}

.continue-btn button {
    outline: none;
}

.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 10px;
    margin-top: 15px;
  }
  
  .switch input { 
    opacity: 0;
    width: 0;
    height: 0;
  }
  
  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: -74px;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: .4s;
    transition: .4s;
    width: 187px;
  }
  
  .slider:before {
    position: absolute;
    content: "";
    height: 16px;
    width: 16px;
    left: 4px;
    bottom: -3px;
    background-color: white;
    -webkit-transition: .4s;
    transition: .4s;
    border: 1px solid grey;
  }
  
  input:checked + .slider {
    background-color: #13985C;
  }
  
  input:focus + .slider {
    box-shadow: 0 0 1px #2196F3;
  }
  
input:checked + .slider:before {
    -webkit-transform: translateX(120px);
    -ms-transform: translateX(120px);
    transform: translateX(162px);
}
<div class="column-input">
          <div class="row-inputs row-inputs-radio">
          
            <div class="row-input">
              <div class="item-size"><bold>Medium</bold></div>       
            </div>
            
            <div class="row-input">
              <label class="switch">
                <input type="checkbox" checked/>
                <span class="slider round"></span>
              </label>
            </div>
            
            <div class="row-input">
              <div class="item-size"><bold>Large</bold></div>
            </div>
            
          </div>

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

Updating the Background Color of a Selected Checkbox in HTML

I have a straightforward question that I've been struggling to find a simple answer for. Can anyone help me with this? Here's the checkbox code I'm working with: <input type="checkbox"> All I want to do is change the backgr ...

encountering an issue: file or directory does not exist, unable to open 'rds-combined-ca-bundle.pem'

I recently downloaded AWS secure socket for my Node server and integrated it into my index.js folder. However, I encountered an error that reads: "Error: ENOENT: no such file or directory, open 'rds-combined-ca-bundle.pem'. Could someone help me ...

The CORS Policy error message "The 'Access-Control-Allow-Origin' header is missing on the requested resource" in Next.js

Encountered an issue with CORS Policy error while attempting to redirect to a different domain outside of the project. For example, trying to navigate to https://www.google.com through a button click or before certain pages load. The redirection was handl ...

What is the process to subscribe and obtain data from a server-to-user channel using pusher-js?

I am currently hosting my application using next.js on Vercel. I want to integrate Pusher to provide real-time messages to users in a private and secure manner. Despite successful log entries, I am facing challenges in subscribing to the channel and retrie ...

The <map> <area> element functions properly only in webkit browsers

Here is some HTML code: <div id="wrap"> <div id="main-content"> <div class="container"> <h1 class="logo">Mysite</h1> <img id="links" src="images/links.png" usemap="map" width="946" heigh ...

Clicking on a checkbox and subsequently removing validation through jquery

Situation : When the 'I am Fresher' checkbox is selected, I want to hide the 'Experience field', but still keep its validation visible so that my form cannot be submitted. My Requirement : When the 'I am fresher' checkbox is ...

Utilize AJAX response to mark checkbox as checked

I have an HTML checkbox that I am attempting to check using a script received as an ajax response. Below is my HTML snippet: <form class="form-vertical sms-settings-form"> <div class="form-group"> <div data-toggle="tooltip" titl ...

Creating a personalized Angular filter to format various object properties in version 1.5

Trying to figure out how to create a custom Angular 1.5 filter to format values of different object properties. The HTML file includes this code inside an ng-repeat: <div>{{::object.day || object.date || 'Something else'}}</div> S ...

challenge encountered while trying to remove ScrollTop feature on mobile gadgets

Currently facing a challenge with responsive design - I have implemented a sticky navbar effect that works seamlessly on desktop, but causes usability issues on mobile. When scrolling down on the mobile version, the sticky navbar obscures the text on the s ...

Issue with Material UI Tab component not appearing in the first position

I've encountered an unusual problem where the first tab is not displaying correctly. To troubleshoot, I added a second tab which appeared perfectly fine. After setting up the second tab to have the desired content of the first tab, I deleted the origi ...

What is the process for saving selected values from a drop-down list into a database?

Hey there, I'm a newcomer to PHP and ajax. When choosing an option from the drop-down list, a separate div function should appear where I need to insert both the selected option and input data in different divs. Sorry for my poor English. Any help fro ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

Troubleshooting Issues with Integrating Bootstrap Carousel

UPDATE: When I attempt to click on either the left or right icons, it unexpectedly scrolls me down to the bottom of the page. It seems to be related to the #truespeed aspect. The carousel functions perfectly when it is on a standalone page but causes issue ...

What is the best way to assign a series of radio buttons to an array within an Angular controller's model?

Let's say I have a controller that contains an array property named 'houses'. I want to use ng-repeat to display this array on a table row with a set of radio buttons (true/false, etc.). How can I ensure that selecting any of these radio but ...

When a user clicks on an element, use jQuery to show a specific

I am looking to extract the Admission ID field within a separate function that triggers when a user clicks on a button. $(document).ready(function () { $.each(data.student, function (i, item){ trHTML += '<tr>'+ ...

Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using ...

Having trouble with Vue component not updating Vuex state before it loads?

At times, the token is committed to Vuex store while other times it is not. userLogin() { axios.post('api/login', this.logindata,) .then(response => { let token = JSON.parse(localStorage.getItem('token')); t ...

Modify the values in a textbox using JavaScript to suit your needs

unusual issue: I'm encountering a strange bug with my form. I have an ajax datepicker attached to a text box, but when I submit the form, all values are received except for those from the datepicker checkboxes. Why is the .Text property empty for th ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

Google Web Toolkit - Update PopupPanel layout upon rotation

I am working on designing a context menu for specific elements utilizing a PopupPanel; the context menu is expected to be quite extensive and intricate. My goal is to have a collection of buttons, an image, and some text associated with the clicked element ...