Reputation: 105
On my webpage (www.reddle.nl/frankendael), I want that when the nav icon (in the left-top of the website) has a class of open
, the navmenu must disappear.
For that I use the following jQuery code:
jQuery(document).ready(function($) {
$('#nav-icon1').click(function(){
$(this).toggleClass('open');
});
if ($('.open').length > 0) {
$('#nav-icon1').click(function(){
$('.main-navigation').css('marginLeft','-999px')
});
} else {
$('#nav-icon1').click(function(){
$('.main-navigation').css('marginLeft','55px')
});
}
});
But it is not working. The nav menu is appearing, but not disappearing. Does anyone know how to solve this?
Upvotes: 0
Views: 37
Reputation: 20626
Use a single click handler with the conditions inside it.
The line of toggleClass()
should be at last, else the if()
condition would work in reverse.
You can further reduce css()
modification by using ternary op.
$('#nav-icon1').click(function(){
$('.main-navigation').css('marginLeft',$(this).hasClass('open') ? '-999px' : '55px')
$(this).toggleClass('open');
});
Upvotes: 0
Reputation: 1630
like this:
jQuery(document).ready(function($) {
$('#nav-icon1').click(function(){
$(this).toggleClass('open');
if ($(this).hasClass('open') {
$('.main-navigation').css('marginLeft','-999px')
} else {
$('.main-navigation').css('marginLeft','55px')
}
});
});
edit if you wanna run it with more css:
jQuery(document).ready(function($) {
$('#nav-icon1').click(function(){
$(this).toggleClass('open');
$('.main-navigation').toggleClass('main-navigation-margin-left');
});
});
Upvotes: 1