user1863502
user1863502

Reputation: 49

javascript - one button three functionsn

First i want to say that i am a newbie in the javascript world.

I want to write a function for a button:

when button is pushed -> x=0 ; post(x); display x;
when button is released -> x=1; post(x); display x;
when button is hold down -> while hold: 
            if(x=0){post(x); display x; x++}          
            if(x=1){post(x); display x; x--} 

This is what i have come up with so far:

http://pastebin.com/1myT891h

Help would be appreciated very much.

Upvotes: 3

Views: 106

Answers (3)

Anders
Anders

Reputation: 15397

Try this fiddle:

Html:

<button id="button">Click here</button><br/>
Status: <span id="status"></span>

Javascript:

observeTriState("#button", function(state) {
    var states = { '0':'Push', '1':'Release', '2':'Hold Down' };

    $("#status").text(states[state]);
}, 500);

function observeTriState(selector, callback, holdDelay) {
    var mouseDown = false;
    var mouseIn = false;
    var interval;

    function checkStatus() {
        if (mouseDown && mouseIn) {
            callback(2)
        }
    }

    $(selector).mousedown(function() {
        callback(0);
        mouseDown = true; 
        interval = setInterval(checkStatus, holdDelay); 
    }).mouseup(function() {
        mouseDown = false;
        callback(1);
        clearInterval(interval);
    }).mouseenter(function() {
        mouseIn = true;
    }).mouseleave(function() {
        mouseIn = false;
        mouseDown = false;
        clearInterval(interval);
        callback(1);
    });
}

Upvotes: 2

Jason L.
Jason L.

Reputation: 2484

Check the following jsFiddle. It does what you're looking for (at least, I hope it does). Let me know if it's not clear and I'll see if I can clear it up a bit.

http://jsfiddle.net/s9nUr/

Here's the code from the fiddle, if you're not interested in seeing it in action. Please note the use of jQuery.

var x= 0;
var interval;

var push = function(val) {

}

var hold = function() {
    if ( x === 0 ) {
        console.log('x is 0');    
    }
    if ( x === 1 ) {
        console.log('x is 1');        
    }
}

$('#myButton').on('mousedown', function() {
    x= 0;
    push(x); 

    interval = setInterval(hold, 500);
});

$('#myButton').on('mouseup', function() {
    x = 1;        
    push(x); 

    clearInterval(interval);
});

Upvotes: 1

luchosrock
luchosrock

Reputation: 708

maybe creating one function with 2 arguments: value and action. so when button is pushed -> myfunction(x,"pushed") ... and so on.

Upvotes: 0

Related Questions