Stefano Maglione
Stefano Maglione

Reputation: 4160

Javascript listen two events and fire one function

how can I listen for two distinct events and only when all two events are detected fire a function?

Upvotes: 3

Views: 6822

Answers (6)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24650

You have many options.

For example: (without using any library)

(function(){
a=false; b=false;
function doIt(){
alert('both function have fired')
}
document.onclick=function (){a=true;if(a&&b) doIt()}
document.onmouseout=function (){b=true;if(a&&b) doIt()}

})()

JsFiddle: http://jsfiddle.net/3nDds/ You need to click inside the document, and move out the document.

Upvotes: 1

jnoreiga
jnoreiga

Reputation: 2174

Another option would be to use the data attribute.

http://jsfiddle.net/vpA3A/3/

$("#mybutton").on("mouseover", function(event) {
    var $button = $(this);
    $button.data("mouse", true);
    dowork($button);
}).on("click", function(event) {
    var $button = $(this);
    $button.data("click", true);
    dowork($button);
});

function dowork($button)
{
    if($button.data("mouse") == true && $button.data("click") == true) {
        alert('both events');
        $button.data('mouse', false).data('click', false);
    }
}

Upvotes: 0

a coder
a coder

Reputation: 544

If it's two states place the function calls inside each other after the first event listener.

Upvotes: -1

Adrian Toma
Adrian Toma

Reputation: 547

This functions are created:

    var got = { first : 0, second : 0 };
    function fire(event_type)
    {
      got[ event_type ] = 1;
      if( got.first && got.second )
      {
        //do stuff and reset
         got = { first : 0, second : 0 };
      }
    }

This is the listener part:

    document.onclick=function (){fire('first');}
    document.onmouseover=function (){fire('second');}

Upvotes: 3

spender
spender

Reputation: 120528

This is where Promises excel:

var prom1 = new Promise(function(resolve, reject){
    $("foo").one("someEvent", resolve);
});
var prom2 = new Promise(function(resolve, reject){
    $("bar").one("otherEvent", resolve);
});
Promise.all([prom1, prom2]).then(function(){
    //woo!
});

Upvotes: 4

Scott Hunter
Scott Hunter

Reputation: 49920

Detect them both, record when you've received one, and check to see if the other has already been received (which means BOTH have been received). Remember to "forget" about them when this happens.

Upvotes: 2

Related Questions