0

I've got an interesting one here.

What I have are a few DIVs that contain hidden input values. I'd like the user to be able to "mousedown" on one of the DIVs and JQuery would get the "id" of the input within that specific DIV. (would be block-1, block-2, block-3, etc).

Here are those DIVs

<div class="block" id="1"><input id="block-1" value="3" type="hidden"></div>
<div class="block" id="2"><input id="block-2" value="3" type="hidden"></div>
<div class="block" id="3"><input id="block-3" value="3" type="hidden"></div>

Now that JQuery's got the correct input id, I'd like to decrease the value by 1 every 200 milliseconds or so as long as mousedown is still active. But if the user releases (mouseup), then that value would reset to the original (3, in this case).

If you're wondering why I'd want this, my original plan was to have the selected DIV change colors or content as the value decreases. If the value eventually hits 0, though, then the DIV will be hidden.

I was trying to work from this, but I kept getting stumped.

Community
  • 1
  • 1
Aaron
  • 531
  • 3
  • 8
  • 22
  • make the selector `$('#'+id+':active')` the `:active` pseudo class applies while holding the left mouse button down – iam-decoder Aug 19 '15 at 19:52

1 Answers1

0

You can use setInterval instead of setTimeout for this.

JS

$("input").mousedown(function(e) {
    var self = $(this);
    clearInterval(this.downTimer);
    this.downTimer = setInterval(function() {
      self.val(self.val() - 1);
    }, 200);
}).mouseup(function(e) {
    clearInterval(this.downTimer);
    var val = $(this).prop("defaultValue");
    $(this).val(val);
});

Fiddle

Note: On the example I used type=text instead of type=hidden so it is visible for testing.

Robin Carlo Catacutan
  • 13,249
  • 11
  • 52
  • 85
  • Awesome, works great. The only changes I made were: $("div").mousedown, along with: $(this).children('input') so the user could mousedown on the DIV instead of just the input area. – Aaron Aug 20 '15 at 01:04