Reputation: 4479
I am trying to trigger a handler only if two events fire (ie. scroll
AND mousewheel
) from the same single action.
My first attempt is was:
$('#right-nav').on('scroll mousewheel', function(event){ console.log('Fired') })
However here it's possible to trigger scroll
without mousewheel
, and to trigger mousewheel
without scroll
. Also If you trigger both, the function will execute twice.
I would like to execute only if the mousewheel
also triggers scroll
, put simply, to catch the "single action that produced both events"
or vice versa, to execute only if mousewheel
does Not trigger scroll
Is this possible? Is there anyway to tell if other events are coming?
Here is a playground jsFiddle: https://jsfiddle.net/o2gxgz9r/8028/
Upvotes: 1
Views: 102
Reputation: 5660
Expanding on @neojg's answer:
var scroll = false, mouse = false;
$(something).on('scroll', function(){
if (mouse){
// do the task I need for both events
}
else{
scroll = true ;
window.setTimeout(function(){ scroll = false ; }, 100);
}
});
$(something).on('mousewheel', function(){
if (scroll){
// do the task I need for both events
}
else{
mouse = true ;
window.setTimeout(function(){ mouse = false ; }, 100);
}
});
Upvotes: 0
Reputation: 221
There is no way to trigger two (or more) events at once. But you always may think of the sequence of events if they may be related etc. Remember that the JavaScript is a single thread so e.g. suppose that scroll event shall be before or after mousewheel event but within 100ms I will do:
var eventHappened = false ;
$(something).on('scroll', function(){
if (eventHappened){
// do the task I need for both events
}
else{
eventHappened = true ;
window.setTimeout(function(){ eventHappened = false ; }, 100);
}
});
$(something).on('mousewheel', function(){
if (eventHappened){
// do the task I need for both events
}
else{
eventHappened = true ;
window.setTimeout(function(){ eventHappened = false ; }, 100);
}
});
Upvotes: 1