Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active September 27, 2015 22:15
Show Gist options
  • Save ernestlv/a0c2aee9c8b3b499af3d to your computer and use it in GitHub Desktop.
Save ernestlv/a0c2aee9c8b3b499af3d to your computer and use it in GitHub Desktop.
Times mouse events to display mega dropdowns smooth and fast. By default waits half a sec to trigger the menu.
function desktop($trigger, id){
var $menu = $trigger.find('+ .dropdown-menu'), delay=st.delay, delay2 = ~~delay/3;
//bootstrap catches the click event so we need to jump to the link here
$trigger.on('click', function(e){
clearTimeout(waiting[id]);
if (id === inside){
inside = 0;
//we need to trigger click tracking since click event is not fired
//we need to send originalEvent since analytics is expecting it.
$trigger.trigger({
type:'click.analytics',
originalEvent: {}
});
}else{
inside = id;
}
location = $trigger.attr('href');
});
$trigger.on('mouseenter', function(e){
if (!inside){ //enter menu 4 the 1st time
waiting[id] = setTimeout(function(){
$trigger.dropdown('toggle');
inside = id;
}, delay);
}else if (id !== inside){ //switch menu
waiting[id] = setTimeout(function(){
clearTimeout(waiting[inside]); //cancel prev menu toggle only if current menu toggle will happen
$trigger.dropdown('toggle');
inside = id;
}, delay2);
}else{ //comming back from dropdown area
clearTimeout(waiting[id]); //cancel toggle
}
});
$trigger.on('mouseleave', function(e){
if ( inside === id ){ //if true current menu was open i might need to close it
waiting[id] = setTimeout(function(){
$trigger.dropdown('toggle');
inside = 0;
}, delay);
}else{ //happens in quick move. menu was never opened.
clearTimeout(waiting[id]); //cancel toggle
}
});
$menu.on('mouseenter', function(){ //enter dropdown area
clearTimeout(waiting[id]); //cancel toggle
});
$menu.on('mouseleave', function(){ //leaving dropdown area i might need to close menu
waiting[id] = setTimeout(function(){
$trigger.dropdown('toggle');
inside = 0;
}, delay);
});
}
var waiting={}, inside=0;
$(st.bindTo).each(function(i, el){
var $trigger = $(el); //bind to each menu link
var id = ~~(Math.random() * (1000000 - 1) + 1); //menu id
if('ontouchstart' in window || 'createTouch' in document || window.navigator.msMaxTouchPoints > 1){
tablet($trigger, id);
}else{
desktop($trigger, id);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment