Last active
March 23, 2020 17:19
-
-
Save dvinciguerra/a5b42ce5e7c0dd6811eb to your computer and use it in GitHub Desktop.
Bootstrap Modal Pure JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
"use strict"; | |
/** | |
* Bootstrap Modal Js Class | |
* @dvinciguerra | |
*/ | |
var Modal = function(el, options) { | |
var self = this; | |
this.el = document.querySelector(el); | |
this.options = options; | |
try { | |
var list = document.querySelectorAll('#'+this.el.id+' [data-dismiss="modal"]'); | |
for (var x = 0; x < list.length; x++){ | |
list[x].addEventListener('click', function(e){ | |
if(e) e.preventDefault(); | |
self.hide(); | |
}); | |
} | |
} | |
catch(e){ | |
console.log(e); | |
} | |
}; | |
/** | |
* Methods | |
*/ | |
Modal.prototype.show = function() { | |
var self = this; | |
// adding backdrop (transparent background) behind the modal | |
if (self.options.backdrop) { | |
var backdrop = document.getElementById('bs.backdrop'); | |
if (backdrop === null) { | |
backdrop = document.createElement('div'); | |
backdrop.id = "bs.backdrop"; | |
backdrop.className = "modal-backdrop fade in"; | |
document.body.appendChild(backdrop); | |
} | |
} | |
// show modal | |
this.el.classList.add('in'); | |
this.el.style.display = 'block'; | |
document.body.style.paddingRight = '13px'; | |
document.body.classList.add('modal-open'); | |
}; | |
Modal.prototype.hide = function() { | |
var self = this; | |
// hide modal | |
this.el.classList.remove('in'); | |
this.el.style.display = 'none'; | |
document.body.style = ''; | |
document.body.classList.remove('modal-open'); | |
// removing backdrop | |
if (self.options.backdrop) { | |
var backdrop = document.getElementById('bs.backdrop'); | |
if (backdrop !== null) document.body.removeChild(backdrop); | |
} | |
}; | |
/* USAGE: */ | |
document.addEventListener('DOMContentLoaded', function(){ | |
var m = new Modal('#MyModal', { | |
backdrop: true | |
}); | |
document.getElementById('btn-open').addEventListener('click', function() { | |
m.show(); | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
USAGE:
document.addEventListener('DOMContentLoaded', function(){
// new modal instance
var modal = new Modal('#MyModal');
// open modal when button clicked
document.getElementById('btn-open').addEventListener('click', function(){
modal.show();
});
});