I am creating a menu structure that when clicking on the element, will display a submenu.
I need to do this using addClass
, since I need to change the styling of the elements when clicking.
When clicking inside the submenu, it should remain open, but it should be closed if you click on the parent element of the submenu or anywhere else.
Follow the structure
HTML:
<div class="menu_btn">
<a href="#">Botão</a>
<div class="submenu">
<ul>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
<li>Item</li>
</ul>
</div>
</div>
CSS:
.menu_btn a{
color:#000;
background:#fff;
text-decoration:none;
border:1px solid transparent;
padding:5px;
}
.hover a{
color:red;
border:1px solid red;
border-bottom:0
}
.submenu{
display:none;
max-width:200px;
border:1px solid red;
margin-top:3px
}
.hover .submenu{
display:block;
}
JQuery:
$(document).ready(function(){
$(".menu_btn").click(function(e){
var e=window.event||e;
$(this).addClass("hover");
e.stopPropagation();
});
$(document).click(function(e){
$('.menu_btn').removeClass("hover");
});
});