Skip to content

Instantly share code, notes, and snippets.

@lysender
Created August 17, 2023 16:41
Show Gist options
  • Save lysender/879b76df4fcc01cf50ac0b76b5353253 to your computer and use it in GitHub Desktop.
Save lysender/879b76df4fcc01cf50ac0b76b5353253 to your computer and use it in GitHub Desktop.
hyperscript - Toggle Hamburger Menu for mobile browsers

How to toggle hamburger menu on/off in hyperscript?

I used this JavaScript solution earlier - https://gist.github.com/lysender/bc9800e6350e1ccfab3c6ce6934b1cd2

However, I realized it is way more simple to just use hyperscript.

What it does is toggle the is-active class on two divs related to the navigation menu.

No need to write the complicated JavaScript code but we do need to include the hyperscript JavaScript file in our page.

<nav class="navbar is-dark" role="navigation" aria-label="main navigation">
  <div class="navbar-brand">
    <a class="navbar-item" href="/">
        Brand
    </a>

    <% if (user) { %>
      <a
        _="on click toggle .is-active on .navbar-menu-header-group"
        role="button"
        class="navbar-burger navbar-menu-header-group"
        aria-label="menu"
        aria-expanded="false"
        data-target="main-menu"
        id="main-menu-burger">
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
          <span aria-hidden="true"></span>
      </a>
    <% } %>
  </div>

  <% if (user) { %>
    <div class="navbar-menu navbar-menu-header-group" id="main-menu">
      <div class="navbar-end">
        <div class="navbar-item">
          <div class="buttons">
            <a
              _="on click remove .is-active from .navbar-menu-header-group"
              class="button is-light"
              hx-post="/logout"
              hx-swap="innerHTML">
                Log out
            </a>
          </div>
        </div>
      </div>
    </div>
  <% } %>
</nav>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment