2
I am creating a menu structure that clicking on the element will display a submenu.
I need to do this using addClass
, because I need to change the stylization of the elements by clicking.
When clicking inside the submenu, it should remain open, but it should be closed if clicking on the parent element of the submenu or anywhere else outside.
Follows 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");
});
});
You can use Hide and show, or toggle to show/hide the menu when clicking the button
– Franchesco
http://jsfiddle.net/q0qvd6yx/ Some modifications.
– Franchesco
Earendul thank you for answering. I’ve tried several ways to execute what I need, but when clicking on the element, I need to give it another styling, changing font color, background, etc. For this I need to use addClass. I also need the submenu to be active, because in the project, some submenus will have forms and things like that. In your Fiddle they close by clicking inside the submenu. Anyway thank you for answering. Thank you so much.
– Mauro Alves
Mauro, try to improve and clarify the own question when questions or misunderstandings arise. It is easier to see everything there than spread in comments.
– brasofilo