TasteMyBiceps
TasteMyBiceps

Reputation: 73

How to control timer with mousedown in jQuery?

My purpose is let user click on the button, when user click, the field shows 4, when user click and hold more than 1 sec, the field shows 4.5. Here is my code:

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
            $(document).ready(function(){
                $("#btn").mousedown(function(e) {
                    clearTimeout(this.downTimer);   
                    this.downTimer = setTimeout(function(){
                        $("#inp").val("4.5");   
                    }, 1000);
                }).mouseup(function(e) {
                    clearTimeout(this.downTimer);

                    // if no the holding is less than 1 sec, 
                    // then nothing will be set, when mouseon, 4 is set to the field.
                    var el = document.getElementById('inp')
                    if(el.value == ""){
                        $("#inp").val("4");
                    }       
                });
            });
        </script>
    </head>
    <body>
        <input type="text" id="inp">
        <button id="btn">4</button>Good
    </body>
</html>

However, my code has limitations, when 4.5 is set, it can never be set back to 4. Is there anyway to solve this? I have a idea whcih is if I can control some variable that represent the timer, then I can use if condition to accomplish this task. Is this possible in jQuery?

Upvotes: 1

Views: 91

Answers (1)

Artur Filipiak
Artur Filipiak

Reputation: 9157

The problem is that the condition if(el.value == "") will not be true because input field is not empty (it already has "4.5" value on mouseup)

The solution is pretty simple.
You have to set field value to 4 and setTimeout while mouse is down. Then clear the timeout on mouseup

var downTimer;
$("#btn").mousedown(function(e) {
    $("#inp").val("4"); 
    clearTimeout(downTimer);   
    downTimer = setTimeout(function(){
        $("#inp").val("4.5");
    }, 1000);
}).mouseup(function(e) {
    clearTimeout(downTimer);
});

JSFiddle

Upvotes: 2

Related Questions