I haven't needed to use a lot of javascript for the relatively simple webpages that I have built in the past, but I am now working on a school project which I want to be responsive. When the page gets below a certain width, the nav is replaced with a button. When this button is clicked, the nav appears below the button, or it is supposed to anyways.
To do this, I first tried to use JQuery's .slideDown()
and .slideUp()
. These worked well for displaying and hiding the nav, but if the page got resized after they had been clicked, the nav didn't show up for some reason. I started looking into the reason for this, but didn't find anything. If anybody has any ideas on why that didn't work, that would be great, but this isn't the point of my question.
I then decided to try and just show and hide the nav manually. Here is my code.
var displayed = false;
$("#menuImage").click(function(){
if (displayed = false) {
$("nav").css("display", "inline-block");
displayed = true;
} else {
$("nav").css("display", "none");
displayed = false;
}
});
$(window).resize(function(){
if ($(window).width >= 880) {
$("nav").css("display", "inline-block");
}
});
nav {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<img id="menuImage" src="http://www.dragonmath.net/summer_project_2016/images/menu.png" alt="menu" />
<nav>
<ul id="navList">
<li class="navListItem">
<a class="navListItemLink" href="../">Home</a>
</li>
<li class="navListItem">
<a class="activeNavListItemLink" href="">Summary</a>
</li>
<li class="navListItem">
<a class="navListItemLink" href="../theme">Theme</a>
</li>
<li class="navListItem">
<a class="navListItemLink" href="../medium">Relation to Other Medium</a>
</li>
</ul>
</nav>
How I read the javascript is:
->Set a global variable named displayed and set it equal to false.
->When the image is clicked (I have tried it with other code, and this piece definitely works)
->Check if the variable displayed is false
->If it is, display the nav and set displayed to true.
I have read up on global variables from here, here, and here, and while the first two question seem to have other problems than with where the variables are set, looking at the differences in their code verses mine, I couldn't find what I was doing wrong.
Because I am very new to javascript, I am certain I am just making a silly error, but it would be great if someone would point out what it was. Also, The function for setting the display
to inline-block
when the page gets bigger than the responsive zone doesn't work. I believe it is probably a similar error, but I have had no luck tracing down its cause.
Other Sources: http://www.w3schools.com/jquery/jquery_css.asp http://www.w3schools.com/jquery/jquery_selectors.asp
Thanks again for any help you can offer!