JavaScript for Bulma Dropdown


This post is for those who do not want to write their own JavaScript code, and just want to use the same code as that in Bulma official website [1].

The JavaScript code comes from main.js used in the official site [2]. I put the code here in the post for easy search by Google or other search engines.

If you do not want to toggle with JavaScript, you can use pure css solution. See [3].

'use strict';

document.addEventListener('DOMContentLoaded', function () {

  // Dropdowns

  var $dropdowns = getAll('.dropdown:not(.is-hoverable)');

  if ($dropdowns.length > 0) {
    $dropdowns.forEach(function ($el) {
      $el.addEventListener('click', function (event) {
        event.stopPropagation();
        $el.classList.toggle('is-active');
      });
    });

    document.addEventListener('click', function (event) {
      closeDropdowns();
    });
  }

  function closeDropdowns() {
    $dropdowns.forEach(function ($el) {
      $el.classList.remove('is-active');
    });
  }

  // Close dropdowns if ESC pressed
  document.addEventListener('keydown', function (event) {
    var e = event || window.event;
    if (e.keyCode === 27) {
      closeDropdowns();
    }
  });

  // Functions

  function getAll(selector) {
    return Array.prototype.slice.call(document.querySelectorAll(selector), 0);
  }
});

Demo:





Tested on:

  • Chromium 63.0.3239.84 on Ubuntu 17.10 (64-bit)
  • Bulma 0.6.2

References:

[1]Dropdown | Bulma: a modern CSS framework based on Flexbox
[2]https://bulma.io/lib/main.js?v=201801161752
[3]Pure CSS Bulma Dropdown Toggle