Interactive hamburger menu using Tailwind

Viewed 4834

I would like to achieve a dropdown menu once the hamburger SVG is clicked. I am using Tailwind with the TALL Stack. Most Tailwind tutorials or posts I have come across are utilizing Vue.Js which I am not using in this project.

Here is my code, I am hoping someone can point me in the right direction.

<button type="button" id="hamburgerbtn" class="hover:text-white focus:outline-none focus:text-white">
<div class="hidden mt-3 md:flex md:flex-row" id="mobileMenu">
<style>
    .active{
        display: block;
    }    
</style>

<script>
    let hamburger = document.getElementById('hamburgerbtn');
    let mobileMenu = document.getElementById('mobileMenu');

    hamburger.addEventListener('click', function(){
        mobileMenu.classList.toggle('active');
    });
</script>
2 Answers

Solution

Here is the Javascript to toggle the menu:

<script>
    document.getElementById('nav-toggle').onclick = function(){
        document.getElementById("nav-content").classList.toggle("hidden");
    }
</script>
<nav id="menu-toggle" 
<button type="button" id="hamburgerbtn"> 
<div class="hidden mt-3 md:flex md:flex-row" id="mobileMenu">
<style>
  .active {
    display: block;
  }
</style>

<script type=module>
  let hamburger = document.querySelector('#hamburgerbtn') 
  let mobileMenu = document.querySelector('#mobileMenu')

  hamburger.addEventListener('click', event => mobileMenu.classList.toggle('active')
  )  
</script>

Here is the tailwind CSS hamburger menu with alpline.js

HTML

<div class="min-h-screen bg-gray-400 flex flex-col justify-center">
<div class="relative py-3 sm:max-w-xl mx-auto">
    <nav x-data="{ open: false }">
        <button class="w-14 h-14 relative focus:outline-none bg-red-600 rounded" @click="open = !open">
           
            <div class="block w-5 absolute left-6 top-1/2   transform  -translate-x-1/2 -translate-y-1/2">
                <span  class="block absolute h-0.5 w-7 text-white bg-current transform transition duration-500 ease-in-out" :class="{'rotate-45': open,' -translate-y-1.5': !open }"></span>
                <span  class="block absolute  h-0.5 w-5 text-white bg-current   transform transition duration-500 ease-in-out" :class="{'opacity-0': open } "></span>
                <span  class="block absolute  h-0.5 w-7 text-white bg-current transform  transition duration-500 ease-in-out" :class="{'-rotate-45': open, ' translate-y-1.5': !open}"></span>
            </div>
        </button>
    </nav>
</div>

Try tested code here - https://bbbootstrap.com/snippets/tailwind-css-hamburger-menu-animation-82889170

Related