Bulma navbar hamburger and svelte

2019-12-27

Bulma provides a fairly involved Javascript snippet for toggling the menu when you hit the hamburger menu. With svelte, things get much simpler.

tl;dr

In <script>...</script>

// Add a handler in the script section
let menuactive='';
function toggleMenuActive() {
  menuactive = (menuactive=='')?
    'is-active'
    :'';
}

In <nav>...</nav>

<!-- Add a handler to the hamburger button -->
<button class="button is-white navbar-burger"
        on:click={toggleMenuActive}>
  <span /><span /><span />
</button>

<!-- ... -->
<!-- ... add a "reactive" class to the actual menu -->
<div class="navbar-menu {menuactive}">
    <!-- ... -->
</div>

Full example

let menuactive='';
function toggleMenuActive() {
menuactive = (menuactive=='')?'is-active':'';
}
<div class="block">
  <nav class="navbar">
    <div class="navbar-brand">
      <a href="#" class="navbar-item">
        <h1 class="title is-4">My brand</h1>      
      </a>
      <button class="button is-white navbar-burger" 
              on:click={toggleMenuActive}>
        <span />
        <span />
        <span />
      </button>
    </div>

    <div class="navbar-menu {menuactive}">
      <div class="navbar-start">
        <a href="#" class="navbar-item"> Home </a> 
        <a href="#" class="navbar-item"> About </a> 
        <a href="#" class="navbar-item"> Contact </a> 

        <div class="navbar-item has-dropdown is-hoverable">
          <a href="#" class="navbar-link">Others</a>

          <div class="navbar-dropdown is-dark">
            <a href="#" class="navbar-item">More</a>
            <a href="#" class="navbar-item">Items</a>
            <a href="#" class="navbar-item">Here</a>
          </div>
        </div>
      </div>
      
      <div class="navbar-end">
        <div class="navbar-item">
          <div class="buttons">
            <a href="#" class="button is-primary">
              <strong>Sign up</strong>
            </a>
            <a href="#" class="button is-light">
              <strong>Log in</strong>
            </a>
          </div>
        </div>
      </div>
    </div>
  </nav>
</div>