Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adapt my js code to an input

I have this javascript code that creates a slider:

http://jsfiddle.net/samccone/ZMkkd/

Now, i want to use this code on a checkbox input. the problem is that the code creates a child element that slides in it's parent using a css position, and an input cannot have a child.

My idea was to use background-position and just slide the background of the input from left to right using css instead of using real positioning.

How can I adapt this script? It is quite easy I think but after a couple of tries I just gave up, i'm not good enough :).

Thanks for your help,

Christopher

like image 397
cmplieger Avatar asked Feb 27 '26 22:02

cmplieger


1 Answers

Believe it or not, for checkboxes a switch effect is possible to create without JavaScript.

If you follow your checkbox with a label:

<input type="checkbox" id="jim" />
<label for="jim"></label>

You will find that you can select the label with the next sibling selector:

input + label { /* some CSS */ }

Why is that useful? Because using the pseudo selector :checked you can now style the label based on the state of the checkbox:

input + label { background-position: 0 0; }
input:checked + label { background-position: 100% 0; }

Clearly, due to the for="jim" attribute, clicking on the label will change the state of the checkbox. So if you hide the checkbox, you end up with a styled, clickable label.

input { display: none; }

Of course, labels can have children so you can be as fancy as you want with your recreation of a switch. And you should be careful to include :focus styles as well, for people who tab to your checkbox rather than click on it.

For browsers that do not support the :checked pseudo class (IE8 and below), it's pretty easy to emulate with a global handler and a 'checked' class. Something like:

jQuery(document).bind('change', function(e){
  var elem = jQuery(e.target);

  // If this is not a checkox, do nothing.
  if (elem.attr('type') !== 'checkbox') { return; }

  // Add or remove checked class based on current state.
  if (elem.attr('checked')) { elem.removeClass('checked'); }
  else { elem.addClass('checked'); }
});

...should do it.

like image 193
stephband Avatar answered Mar 02 '26 13:03

stephband



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!