0

I am developing a web application (using AngularJS) and I need to create a Toggle Switch. The guides on the web don't seem difficult, and I followed the one from W3C: https://www.w3schools.com/howto/howto_css_switch.asp

In this guide everything is ok: I can click wherever I want within the Toggle Switch area and it behaves as it should. Behind it, obviously, there must be a checkbox type input.

Unfortunately, this does not happen in my application. This is my code (I used <div> instead <label> because label already have a proper style):

<style>
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.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);
}

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

.slider.round:before {
  border-radius: 50%;
}
</style>
 
<div class="switch">
    <input type="checkbox">
    <span class="slider round"></span>
</div>

As you can see, this is the exact same W3C code (except that I don't obscure the input, otherwise nothing would happen in my case!). Unfortunately what happens is the following thing:

enter image description here enter image description here

The style is perfect, but the behavior is only right by clicking in the small left corner (which would be the input checkbox that was purposely not obscured!). If I make the checkbox input invisible as suggested by the W3C, I can no longer click in that corner and nothing happens!

I don't understand how to make the input checkbox invisible but still extend its behavior to the whole Toggle Switch! Where am I wrong?

2
  • 1
    “Where am I wrong?” - in replacing an element that had a very specific purpose, when it comes to form fields (label), with one that has no such specific purpose at all (div). Commented Nov 20, 2020 at 12:10
  • 1
    “because label already have a proper style” - the choice of what the correct HTML element is for a given purpose, should never rely on aspects like this. Commented Nov 20, 2020 at 12:11

1 Answer 1

1

you need to use <label> instead

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.