Reputation: 117
Show element works fine, however nothing happens when trying to hide same element.
HTML after showing element:
$(".container").click(function() {
$('.top-menu').css('display', 'block');
});
$("div.container.change").click(function() {
$('.top-menu').css('display', 'none');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container change" onclick="myFunction(this)">
<nav class="top-menu" style="display: block;">
enter code here
Really looks to be basic as hell, but I do not see why it's not working. Thanks for reviewing.
Upvotes: 0
Views: 848
Reputation: 2008
Just bind the click handler to the container element (see below) and remove the inline onclick
attribute. You can use .hide
and .show
as a shorthand for .css('display', 'none')
and .css('display', 'block')
.
If you need to toggle the display then use .toggle
on the menu element.
$(document).ready(function(){
// ref container
var container = $('.container'),
// cache the menu selector
menu = $('.top-menu');
container.on('click', function(){
menu.hide();
});
});
// you can use menu.toggle(); to show/hide on container click
.container {
background: green;
padding: 10px;
}
.top-menu {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<nav class="top-menu">
Enter code here
</nav>
</div>
Upvotes: 2
Reputation: 2403
REMOVE THE ONLICK FUNCTION THAT YOU CALL ON THE HTML.It will work.
$(".container").click(function() {
$('.top-menu').css('display', 'block');
});
$("div.container.change").on('click',function() {
$('.top-menu').css('display', 'none');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container change">
<nav class="top-menu" style="display: block;">
enter code here
</nav>
</div>
Upvotes: 0