mercredi 30 janvier 2019

Checkbox on mousedown, uncheck on mouseup

I am making jQuery application where there is a checkbox that is checked only when the mouse/key/touch is pressed. Check on mousedown, uncheck on mouseup.

Even if I use event.preventDefault(), the checkbox remains checked if the mouse button is not down, but the spacebar works fine.

$(function() {
  var cb = $("input");
  cb
    .on("mousedown keydown", function(event) {
      event.preventDefault();
      cb.prop("checked", true);
    })
    .on("mouseup keyup", function(event) {
      event.preventDefault();
      cb.prop("checked", false);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type=checkbox autofocus>

I know the code above needs a bit of work to work correctly in any situation (touch, etc.) but it is written for testing purposes only




Aucun commentaire:

Enregistrer un commentaire