jQuery dropdown menu with hover intent and touch events
A touch-enabled jQuery dropdown menu with hover intent for mouse events.
HTML
<ul class="menu">
<li class="dropdown">
<a href="#" class="toplevel">menu</a>
<ul class="submenu">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
</ul>
</li>
<li class="dropdown">
<a href="#" class="toplevel">menu2</a>
<ul class="submenu">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4t</a></li>
</ul>
</li>
</ul>
CSS
.menu {
width: 400px;
list-style-type: none;
}
.toplevel {
display: block;
padding: 0 10px;
line-height: 2;
color: #fff;
text-decoration: none;
background: #f00;
}
.dropdown > a.another-color {
background: #eeeeee
}
.dropdown {
position: relative;
z-index: 200;
float: left;
width: 200px;
}
.submenu {
position: absolute;
top: 0;
left: 0;
display: none;
width: 200px;
list-style-type: none;
padding-top: 2em;
z-index: 200;
}
.hover .submenu {
display: block;
}
.submenu a {
display: block;
padding: 5px;
color: #fff;
text-decoration: none;
background: navy;
}
JavaScript
$(function()
{
var $dropdowns = $('li.dropdown');
$dropdowns
.on('mouseover', function()
{
var $this = $(this);
if ($this.prop('hoverTimeout'))
{
$this.prop('hoverTimeout', clearTimeout($this.prop('hoverTimeout')));
}
$this.prop('hoverIntent', setTimeout(function()
{
$this.addClass('hover');
}, 250));
})
.on('mouseleave', function()
{
var $this = $(this);
if ($this.prop('hoverIntent'))
{
$this.prop('hoverIntent', clearTimeout($this.prop('hoverIntent')));
}
$this.prop('hoverTimeout', setTimeout(function()
{
$this.removeClass('hover');
}, 50));
});
});