Making navbar collapse with JS
10,140
first hide the nav bar element using @media and change elements into list view
@media screen and (max-width: 850px){
//replace max width with your width
ul li {
display: block;
}
ul {
display: none;
}
}
Showmenu functions toggles the visibility of nav bar's elements
function showmenu()
{
var x = document.getElementById('myUL');
if (x.style.display == 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
Also add a button to trigger the function
<!DOCTYPE html>
<html lang="en">
<head>
<button onclick = 'showmenu();'>click me to see menu</button>
<ul id='myUL'>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</head>
</html>
Hope this helps
Author by
Charlie
Updated on December 03, 2022Comments
-
Charlie 6 months
Currently my navbar shrinks with the page size, using
@media screen
. This works fine, but when the page is very small I want the navbar to collapse into a vertical drop down which requires a click to open.Due to my circumstances I cannot use bootstrap, just html/css and js.
example on jsfiddle
-
viCky over 5 yearsHi Charlie. This is not a complete question. There is not enough detail regarding what you have tried or implemented. I would request you to do a basic research and try to implement something first. When you are not able to implement any thing, then come to us with details of the issues that you are facing. This will enable us better to help you. See the How to Ask page for help clarifying this question.
-
Charlie over 5 yearsI have tried, every single example of this i can find uses bootstrap, obviously because it's easier but due to my circumstances i cannot use bootstrap. Having a thread like this, with an answer on how to preform this task without bootstrap would be very useful to alot of people in my situation
-
-
Charlie over 5 yearsThanks, but unfortunately i need a solution that doesnt use boot strap