3

JavaScript for Bulma Modal

 2 years ago
source link: https://siongui.github.io/2018/02/11/bulma-modal-with-javascript/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript for Bulma Modal

February 11, 2018

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.

'use strict';

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

  // Modals

  var rootEl = document.documentElement;
  var $modals = getAll('.modal');
  var $modalButtons = getAll('.modal-button');
  var $modalCloses = getAll('.modal-background, .modal-close, .modal-card-head .delete, .modal-card-foot .button');

  if ($modalButtons.length > 0) {
    $modalButtons.forEach(function ($el) {
      $el.addEventListener('click', function () {
        var target = $el.dataset.target;
        var $target = document.getElementById(target);
        rootEl.classList.add('is-clipped');
        $target.classList.add('is-active');
      });
    });
  }

  if ($modalCloses.length > 0) {
    $modalCloses.forEach(function ($el) {
      $el.addEventListener('click', function () {
        closeModals();
      });
    });
  }

  document.addEventListener('keydown', function (event) {
    var e = event || window.event;
    if (e.keyCode === 27) {
      closeModals();
    }
  });

  function closeModals() {
    rootEl.classList.remove('is-clipped');
    $modals.forEach(function ($el) {
      $el.classList.remove('is-active');
    });
  }

  // Functions

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

});

Demo:

Launch image modal



You might be interested in ...


Tested on:

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

References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK