Sebastian Olsen
Sebastian Olsen

Reputation: 10878

jQuery - Bind two events to an AND operator

Is it posible to bind two events to an AND logic operator so that both has to be active for the function to be called? Say I have this:

foobar.bind("foo AND bar", barfunc);

function barfunc(e) {
    alert("foobar!");
}

So in order for barfunc to be called both foo and bar needs to be active. This would be really useful cause I am making a slider/seeker out of divs (Cannot use jquery UI slider) and I need it to call the function when I am both pressing down my mouse button and hovering over the div.

Upvotes: 2

Views: 732

Answers (1)

Ryan Neuffer
Ryan Neuffer

Reputation: 792

It's not possible using syntax like that—the events will never fire at the exact same time, one will always be after the other. That said, you could do something like the following (pseudo code based off your example):

var isHovering = false,
    isClicking = false;

function barfunc(e) {
    if(isHovering && isClicking){
       alert("foobar!");
    }
}

foobar.on('mousedown', function(event){

    isClicking = true;
    barFunc(event);

}).on('mouseup', function(event){

    isClicking = false;

}).on('mouseenter', function(event){

    isHovering = true;
    barFunc(event);

}).on('mouseleave', function(event){

    isHovering = false;

});

Upvotes: 4

Related Questions