I am trying to make a mobile nav button change the menu display from display:none; to display:block; when clicked and then from display:block; to display:none; when clicked again. It works switching from display:none; to display:block; but not from display:block; to display:none;
I am still relatively new to working with javascript, I did try to search around for my answer (i feel it might be out there somewhere), but unless I was implementing some of the other code i found wrong I was not able to get it to function. below is my original attempt at coding it. Thanks for the help
var hidden = true;
if (hidden == true) {
$('a.hamburger').click(function() {
hidden = false;
document.getElementById('navigation').style.display = "block";
document.getElementById('header-menu').style.height = "370px";
});
} else if (hidden != true) {
$('a.hamburger').click(function() {
hidden = true;
document.getElementById('navigation').style.display = "none";
document.getElementById('header-menu').style.height = "78px";
});
};
The correct way of hiding and showing an element in jquery is to use .hide()
and .show()
Example:
$('#id').hide();
$('#id').show();
Or alternatively
$("#id").css("display", "none");
$("#id").css("display", "block");
Or you could use jQuery's .toggle()
. Also, I'm not sure whether it is for some reason a conscious choice to mix your jQuery with vanilla JS, but here is a purely jQuery solution:
$(document).ready(function(){
$('a.hamburger').click(function() {
$('#navigation').toggle();
if ($('#navigation').is(':visible')) {
$('#header-menu').css('height', '370');
} else {
$('#header-menu').css('height', '');
}
});
});
Here's a working example .
Thanks guys for the answers, i was waiting for an email alert that i had responses but never received one so i had asked a friend for help this morning and figured out the problem is that i had 2 click functions when there only needs to be one, here's what worked out:
var $isHidden = true;
$('a.hamburger').click(function() {
if ($isHidden == true){
document.getElementById('navigation').style.display = "block";
document.getElementById('header-menu').style.height = "370px";
$isHidden = false;
} else {
document.getElementById('navigation').style.display = "none";
document.getElementById('header-menu').style.height = "78px";
$isHidden = true;
};
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.