Speakmore Speakmore - 1 year ago 268
CSS Question

Switch Button - switching html

I'm looking for some assistance with a website I'm coding. I have an HTML and CSS switch button (or label):


<label class="switch">
<input type="checkbox"></input>
<div class="slider round"></div>


/* The switch - the box around the slider */
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;

/* Hide default HTML checkbox */
.switch input {display:none;}

/* The slider */
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;


input:checked + .slider {
background-color: #2196F3;

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

input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);

/* Rounded sliders */
.slider.round {
border-radius: 34px;

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

Here is just what the button looks like: https://jsfiddle.net/pbxn2egc/

Essentially what I want or am trying to do is when the button is toggled, I would like for it to show the price of 5 items (that I hard-coded in, so like standard html) and then when you toggle the button it hides that text and shows the competitors price by showing that text.

So if the button is left, I want Walmart's prices. If the button gets toggled to the right, Walmart's prices hide, and Target's appear in the same location.

Can someone assist me with this? Thanks!

Answer Source

One approach is to listen for the onchange event on your <input> element.

Then, when the box is checked/unchecked, you can determine which element (price) is visible and display the other.

document.getElementById("mySwitch").onchange = function() {
  var priceA = document.getElementById("priceA");
  var priceB = document.getElementById("priceB");
  if (priceA.classList.contains("hidden")) {
    priceA.className = "shown";
    priceB.className = "hidden";
  } else if (priceB.classList.contains("hidden")) {
    priceB.className = "shown";
    priceA.className = "hidden";
.shown {

.hidden {
  display: none;
<input type="checkbox" id="mySwitch"></input>
<div class="slider round"></div>

<div id="priceA" class="shown">Price A</div>
<div id="priceB" class="hidden">Price B</div>

If you're using jQuery, there's a toggleClass() method that will automatically toggle an element between two classes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download