Bootstrap: Dropdowns on mouse over
We use Twitter Bootstrap and I wanted our navbar dropdown menus to open automatically on mouse over (hover), so this is a tiny JQuery JavaScript that does that.
Usage
Just put this at the end of your page, before the </body>
tag. The minified script:
<script type="text/javascript">
(function(e,d,b){var a=0;var f=null;var c={x:0,y:0};e("[data-toggle]").closest("li").on("mouseenter",function(g){if(f){f.removeClass("open")}d.clearTimeout(a);f=e(this);a=d.setTimeout(function(){f.addClass("open")},b)}).on("mousemove",function(g){if(Math.abs(c.x-g.ScreenX)>4||Math.abs(c.y-g.ScreenY)>4){c.x=g.ScreenX;c.y=g.ScreenY;return}if(f.hasClass("open")){return}d.clearTimeout(a);a=d.setTimeout(function(){f.addClass("open")},b)}).on("mouseleave",function(g){d.clearTimeout(a);f=e(this);a=d.setTimeout(function(){f.removeClass("open")},b)})})(jQuery,window,200);
</script>
Source & Demo
See this jsfiddle for the complete, readable source and demo.
Features
- tiny code (~0.5k)
- painless to integrate - just add it to your page, done. No config or init needed.
- Menus drop down after a short delay of 200ms (adjustable) to avoid flickering
Caveats
- Works in Chrome, Safari and Firefox, not tested on IE
- Doesn't work properly on iPad Mobile Safari (should turn it off there because there's no hover state on touch devices)
How it works
Very simple. On mouseenter
, the script sets a timer that adds the open
class to the dropdown after 200ms. On mouseleave
, the timer we set in mouseenter
is removed so it doesn't actually fire, and we remove the open
class again.
JavaScript vs. CSS-only
There are CSS only versions that achieve a similar effect, but sadly, those drop down too quickly. I wanted the menus to remain closed when you're just navigating the top bar, and only drop down when you actually stop over a menu for a (very short) while. I tried achieving this effect with CSS3 Transitions, but since those would leave out some older browsers, I ended up with this little JavaScript.
Written by Andreas Pizsa
Related protips
4 Responses
We fully rely on selectboxit for stuff like this:
http://gregfranko.com/jquery.selectBoxIt.js
Thanks, max.
I believe both focus on different aspects and use cases.
The solution I shared here focuses on solving this single specific micro-problem with a tiny copy-and-paste javascript.
selectBoxIt is a full blown, very feature rich package of css and js to customize the look and behavior of standard html-select dropdown menus.
Hi,
How would you go about for the dropdown menu to hang on for a slight delay after the mouse has left? It can be hard to actually catch the menu.
Anyway, thanks a lot for this script, it's exactly what I was looking for!
awesome man it just worked like hot cake .