Fraktar
Fraktar

Reputation: 199

Bootstrap number input spinner won't stop spinning

Demo on Bootsnipp

Issue:

If you hold left click on + or -, then right click, move your mouse away from the + or - button and let go of both clicks, the "mouseup" function will never fire, and it will keep adding or substracting numbers and you can't stop it.

Thoughts?

Thanks in advance!

Upvotes: 0

Views: 750

Answers (2)

J. Titus
J. Titus

Reputation: 9690

Explanations in the code below:

$(function() {
    var action;
    $(".number-spinner button").mousedown(function () {
        btn = $(this);
        input = btn.closest('.number-spinner').find('input');
        btn.closest('.number-spinner').find('button').prop("disabled", false);
        // You're creating a new interval on every mousedown (left and right click)
        // You need to clear the previous interval to make this work.
        clearInterval(action);
        if (btn.attr('data-dir') == 'up') {
            action = setInterval(function(){
                if ( input.attr('max') === undefined || parseInt(input.val()) < parseInt(input.attr('max')) ) {
                    input.val(parseInt(input.val())+1);
                }else{
                    btn.prop("disabled", true);
                    clearInterval(action);
                }
            }, 50);
        } else {
            action = setInterval(function(){
                if ( input.attr('min') === undefined || parseInt(input.val()) > parseInt(input.attr('min')) ) {
                    input.val(parseInt(input.val())-1);
                }else{
                    btn.prop("disabled", true);
                    clearInterval(action);
                }
            }, 50);
        }
    }).mouseup(function(){
        clearInterval(action);
    }).mouseout(() => {
        // Added to stop spinning when mouse leaves the button
        clearInterval(action);
    });
});

Recap:

  1. Clear the previous interval on mousedown.
  2. Clear the interval on mouseout also.

Upvotes: 1

bmceldowney
bmceldowney

Reputation: 2305

The mouseup event will only fire for an element if the mouse is over that element when the mouse button is released.

You could add your handler to the document and then delegate to child controls from there.

Or could just add another handler for mouseout and clear your interval on that event.

Upvotes: 0

Related Questions