12

I'm trying to create a sliding checkbox like the one on the iphone.

I started with this script:

$('input[type=checkbox]').live('touchstart', function (e) {
            down_x = e.originalEvent.touches[0].pageX;
            $('input[type=checkbox]').live('touchmove', function (e) {up_x = e.originalEvent.touches[0].pageX;
            if ((down_x - up_x) > 1)  {$(this).change()}});
            });

But it does not seem to work. Any idea on how to implement this?

cmplieger
  • 7,155
  • 15
  • 55
  • 83

1 Answers1

18

this was a fun little problem

I got it working just fine, it even works with a mouse :)

I tested it on my Ipad and Iphone and it is pretty cool.

would not take much work to flip this into a plugin but this should work just fine for you

the trick with working with ios mobile events is these three events

$('.toggle_box').bind('touchstart',touch_start);
$('.toggle_box').bind('touchmove',touch_move);
$('.toggle_box').bind('touchend',slide_end);   

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

Seth
  • 10,198
  • 10
  • 45
  • 68
samccone
  • 10,746
  • 7
  • 43
  • 50
  • ha no problem, this was pretty fun actually, I think I am going to write up a big blog post about it, but glad you enjoyed it – samccone May 16 '11 at 02:46
  • 1
    I broke this script in like 2 seconds while on the computer with a mouse. I think you need a return false or stop propagation somewhere...I was clicking like crazy and it got stuck in the "green" position and no longer worked. – Alex Aug 02 '11 at 15:24
  • are "touchstart" and "touchend" really necessary? – MartianMartian Jul 06 '16 at 07:12
  • also, in the 'touchmove', is there a way to find out direction of movement? – MartianMartian Jul 06 '16 at 07:14