Skip to content Skip to sidebar Skip to footer

How Do I Add Text To This Css 'switcher' 'toggle Switch'

Here's the actual 'Swticher' Generator: https://proto.io/freebies/onoff/ I'm not clear on how to add text to the event - so when the switch is on default certain text is shown and

Solution 1:

You can copy paste the css used by the site through DevTools. Anyways, what they do is, initially they set the checkbox to checked which makes the margin-left to be 0 which shows the ::before pseudo-element that has "ON" text. And on not checked, margin-left is set to -100% which shows ::after pseudo-element that has "OFF" text.

Here's the relevant CSS -

.onoffswitch-checkbox {
    display: none;
}

.onoffswitch-inner::before {
    content: "ON";
    padding-left: 10px;
    background-color: #34A7C1;
    color: #FFFFFF;
}

.onoffswitch-inner::after {
    content: "OFF";
    padding-right: 10px;
    background-color: #EEEEEE;
    color: #999999;
    text-align: right;
}

.onoffswitch-inner {
    display: block;
    width: 200%;
    margin-left: -100%;
    transition: margin 0.3s ease-in 0s;
}

Here's the entire code in JSFiddle - https://jsfiddle.net/0f4rbLmo/1/

Edit: If you want to toggle a div based on the switch, you can define hidden class like -

.triggeredDiv.hidden {
  display: none;
}

And then trigger it based on checkbox value in javascript when event is fired.

function toggleDiv() {
  if (document.getElementById('myonoffswitch').checked) {
    document.querySelector('.triggeredDiv').classList.remove('hidden');
  } else {
    document.querySelector('.triggeredDiv').classList.add('hidden');
  }
}
document.getElementById('myonoffswitch').addEventListener("change", toggleDiv);

JSFiddle - https://jsfiddle.net/g7qm2txs/


Post a Comment for "How Do I Add Text To This Css 'switcher' 'toggle Switch'"