Hey all I'm building an app with Rails 5, Ruby 2.4.0 and TailwindCss
Im trying to build out a responsive collapsable navbar, however my JS is lacking...
Right now my navbar on large screens is working, and the nav on small and extra small screens is present, however wont collapse to show the menu when I click the button, and im really not too sure where Im going wrong here.
Code Pen:
My code:
<nav class="flex items-center justify-between flex-wrap bg-black p-6 nav-fixed">
<div class="flex items-center flex-no-shrink text-white mr-6"> <!-- Navbar Title Block -->
<span class="font-semibold text-xl tracking-tight">LoadLead</span>
</div>
<div class="block lg:hidden"> <!-- Navbar button -->
<button class="flex items-center px-3 py-2 border rounded text-white border-white hover:text-white hover:border-white" onclick="toggleHidden('mobile')">
<i class="fas fa-bars fill-current h-3 w-3"></i>
</button>
</div>
<div class="w-full block flex-grow lg:flex lg:items-center lg:w-auto xs:hidden sm:hidden" id="mobile">
<div class="text-sm lg:flex-grow">
<a href="#home" class="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-white hover:font-semibold mr-4 nav-link"> Home </a>
<a href="#contact" class="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-white hover:font-semibold mr-4 nav-link"> Contact </a>
<a href="#pricing" class="block mt-4 lg:inline-block lg:mt-0 text-white hover:text-white hover:font-semibold mr-4 nav-link"> Pricing </a>
</div>
<div>
<a href="#SignUp" class="inline-block mt-4 lg:inline-block lg:mt-0 text-white hover:text-white hover:font-semibold mr-4 nav-link">Sign up</a>
</div>
</div>
</nav>
function toggleHidden(e) {
var element = document.getElementById(e);
element.classList.toggle('hidden');
}
答案 0 :(得分:1)
您需要确保按钮上有一个事件监听器来调用该元素。
var button = document.getElementById('button'); // Assumes element with id='button'
button.onclick = function() {
var element = document.getElementById('navbar'); // Assumes element has id of #navbar
element.classList.toggle('hidden');
}
};
编辑: *不要忘记将导航栏和按钮的ID添加到HTML *