Reputation:
I have the following increment / decriment buttons. I want to fire the event when the button is pressed and not only when clicked.
Notice that when you click the button once and hold enter, it does what i want to achive, but it should be done with click.
var Basket = {
plusIncrementButton : $("#plus-btn"),
minusIncrementButton : $("#minus-btn"),
quantityInput : $('#qty_input')
};
/* Increment button */
Basket.plusIncrementButton.on('click',e=>{
Basket.quantityInput.val(parseInt(Basket.quantityInput.val()) + 1 );
});
Basket.minusIncrementButton.on('click',e=>{
Basket.quantityInput.val(parseInt(Basket.quantityInput.val()) - 1 );
if (Basket.quantityInput.val() == 0) {
Basket.quantityInput.val(1);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group mb-3">
<div class="input-group-prepend">
<button class="btn btn-danger btn-sm incbtn" id="minus-btn">decrement</button>
</div>
<input type="number" id="qty_input" class="form-control form-control-sm" value="1" min="1">
<div class="input-group-prepend">
<button class="btn btn-success btn-sm incbtn" id="plus-btn">Increment</button>
</div>
</div>
Upvotes: 3
Views: 1889
Reputation: 156
It can be done by using recursive. I'm using speed
to adjust the speed while incrementing. I'm also adding mouseleave
to prevent the function to keep looping this function when the cursor leave the button. You can do the opposite for decrementing.
EDIT: To get this running on mobile devices, just add touchstart
, touchend
, and touchmove
into the code.
var timeout;
var speed = 500;
// Increment button
$('#plus-btn').on('mousedown mouseup mouseleave', e => {
if (e.type == "mousedown") {
increment(speed);
} else {
stop()
}
});
// Increment function
function increment(speed) {
$('#qty-input').val(parseInt($('#qty-input').val()) + 1);
timeout = setTimeout(() => {
increment(speed * 0.8);
}, speed);
}
function stop() {
clearTimeout(timeout);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="input-group-prepend">
<button class="btn btn-danger btn-sm incbtn" id="minus-btn">decrement</button>
</div>
<input type="number" id="qty-input" class="form-control form-control-sm" value="1" min="1">
<div class="input-group-prepend">
<button class="btn btn-success btn-sm incbtn" id="plus-btn">Increment</button>
</div>
Upvotes: 2