I have a dropdown menu that I have created using CSS and jQuery that I am trying to make dropdown either on on hover and on click.
By default I want the dropdown to be displayed on click, but given the class .dropdown-hover I want it to be displayed when hovered over.
Here is a JSFiddle of what I currently have: http://jsfiddle.net/dR8hL/1/
Right now, no matter what class is applied to the dropdown it is displayed on hover and I am unsure of how to fix that.
HTML
<div class="dropdown dropdown-hover">Dropdown on hover
<ul class="dropdown-menu">
<li><a href="#">Profile</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Log out</a></li>
</ul>
</div>
<div class="dropdown">Dropdown on click
<ul class="dropdown-menu">
<li><a href="#">Profile</a></li>
<li><a href="#">Settings</a></li>
<li><a href="#">Log out</a></li>
</ul>
</div>
CSS
.dropdown {
cursor: pointer;
outline: none;
position: relative;
width: auto;
}
.dropdown .dropdown-menu {
background-color: #fff;
border: 1px solid #eee;
border-radius: inherit;
font-weight: inherit;
left: 0;
margin-left: 0px;
opacity: 0;
pointer-events: none;
position: absolute;
right: 0;
text-transform: none;
width: 200px;
z-index: 99999;
-webkit-transition: all 0.3s ease-in;
-moz-transition: all 0.3s ease-in;
-ms-transition: all 0.3s ease-in;
-o-transition: all 0.3s ease-in;
transition: all 0.3s ease-in;
}
.dropdown .dropdown-menu a { text-decoration: none; }
.dropdown .dropdown-menu p {
margin: 0;
padding: 10px 15px;
}
.dropdown .dropdown-menu span { line-height: inherit; }
.dropdown ul.dropdown-menu { list-style-type: none; }
.dropdown .dropdown-menu li {
display: block;
padding: 5px 10px;
}
.dropdown .dropdown-menu li:hover { background-color: #f3f8f8; }
.dropdown.dropdown-active .dropdown-menu {
opacity: 1;
pointer-events: auto;
}
jQuery
function DropDown(el) {
this.dd = el;
this.initEvents();
}
DropDown.prototype = {
initEvents: function () {
var obj = this;
// Determine if dropdown is on hover or on click
if ($(".dropdown").hasClass("dropdown-hover")) {
// Toggle .dropdown-active on hover
$(".dropdown").mouseenter(function (event) {
$(this).addClass("dropdown-active");
event.stopPropagation();
});
$(".dropdown-menu").mouseleave(function () {
$(".dropdown").removeClass("dropdown-active");
});
} else {
// Toggle .dropdown-active on click
obj.dd.on('click', function (event) {
$(this).toggleClass('dropdown-active');
event.stopPropagation();
});
}
}
}
$(function () {
var dd = new DropDown($('.dropdown'));
$(document).click(function () {
// Remove class from all dropdowns
$('.dropdown').removeClass('dropdown-active');
});
});