JavaScript for Bulma Modal
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:
[1] | Modal | Bulma: a modern CSS framework based on Flexbox |
[2] | https://bulma.io/lib/main.js?v=201802091742 |