📜 ⬆️ ⬇️

Customizing radiobutton without js

Once, I had a task, to make a choice of one of several colors on the site form. It would seem that nothing is easier. The radiobutton element, as well as possible, is suitable for this task, you only need to customize it a little bit. This is where the problems begin. The fact is that the rendering of the radiobutton and checkbutton is not controlled by the browser, but by the OS. Accordingly, most CSS properties (for example, background-color ) do not affect them.

I found a lot of ways to customize radiobutton , but they all seemed too complicated for me, so I decided to create my own.

My idea is based on the fact that when a user clicks on a label , the radiobutton switches. So you can customize not the radiobutton , but the label .

Consider the sample HTML code:
 <input type="radio" name="color" value="#0000ff" id="blue"/> <label for="blue" class="blue"></label> <input type="radio" name="color" value="#00ffff" id="cyan"/> <label for="cyan" class="cyan"></label> 

There is nothing unusual here. Regular radiobutton and signatures to them.
')
Now CSS:
 //  radiobutton input[type="radio"]{display: none;} //  label label{ width: 20px; height: 20px; } label.blue{background-color: blue;} label.cyan{background-color: #00ffff;} //    input[type="radio"]:checked+label{ border: black solid 2px; } 

Here we hide the radiobutton and draw the way we want the label . Draw a label for the marked state input[type="radio"]:checked+label . Everything is simple and elegant.

At this point it would be possible to complete the post, if not for one “but”.

A pair of rotten tomatoes in the direction of Apple

The world would be good and beautiful if it did not have one corporation which has a special path of development. This is Apple, which denies its users the right to poke on the label . As a result, my method does not work on the iPhone and iPad. The most interesting thing is that Safari on Windows chews everything correctly. Unfortunately, there was not a single iMac to check.

Especially for hipsters, I had to use JS (the code is designed to be used in conjunction with jQuery):
  var deviceAgent = navigator.userAgent.toLowerCase(); var iOS = deviceAgent.match(/(iphone|ipod|ipad)/); if (iOS) { $('label').click(function (event) { $('#' + $(event.target).attr('for')).attr('checked', true).change(); }); } 


Usage example

Long Twit is a simple service that renders text into a picture and sends it to Twitter. You can choose the color of the text and background.

Source: https://habr.com/ru/post/150760/


All Articles