Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
This is a modal class that creates a js object containing:
- a parent div, to use for things like dimming the page behind the dialog
- a title H1 containing whatever is passed as the title argument
- a body div containing whatever is passed as the body argument
A callback function will fire when the html is ready, if passed as a third argument.
Built-in methods:
- destroy() removes the dialog from the dom; takes no arguments
- attach() injects html model into the document; accepts a target node as argument;
if no argument provided, the default node target is document.body.
var Modal = function(title, body, callback) {
this.modalContainer = document.createElement('div'); = 'modal-container';
this.modalBox = document.createElement('div'); = 'modal';
this.modalTitle = document.createElement('h1');
this.modalTitle.innerHTML = (title !== null && title !== 'undefined' && typeof(title) === 'string') ? title : 'Modal';
this.modalClose = document.createElement('button');
this.modalClose.innerHTML = 'X';
this.modalBody = document.createElement('div');
if (typeof(body) === 'object') {
this.modalBody.innerHTML = body.outerHTML;
} else if (typeof(body) === 'string'){
this.modalBody.innerHTML = body;
this.destroy = function(){
this.attach = function(ele){
var self = this;
(ele) ? ele.appendChild(this.modalBox) : document.body.appendChild(this.modalBox);
self.modalClose.addEventListener('click', function(){
(callback) ? callback() : null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment