Search code examples
cordovacheckboxtouchstart

Change checkbox toggle function from click to touchstart


I am developing a cordova app. Because of the 300ms delay with the click event I don't want to use that. How do I change the event a <input type='checkbox'> element listens to for toggeling it's checkmark from click to e.g. touchstart?

The closest I got was making the checkbox disabled and adding this code:

$(':checkbox').each(function(){
        $(this).bind('touchstart', function(){
            if(this.checked) {
                this.checked = true;
            } else {
                this.checked = false;
            }
        })
    });

Unfortunately touchstart does not trigger.


Solution

  • for one, I need to call preventDefault() on the caught event.

    The other problem was, that checked is not an actual jquery property of checkboxes, and I need to work with prop()

    So what ended up working was:

    $('.divClassContainingCheckbox').each(function(){
        $(this).bind('touchstart', function(e){
            e.preventDefault();  // prevents click from triggering check
            checkbox = $(this).find(':checkbox');
            if(checkbox.is(":checked")) {
                checkbox.prop('checked', false);
            } else {
                checkbox.prop('checked', true);
            }
        })
    });
    

    HTML:

    <div class='divClassContainingCheckbox'>
        <input type='checkbox' />
    </div>