Skip to content

Instantly share code, notes, and snippets.

@jamesona
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesona/a6c2aee53ffbdffd5cbd to your computer and use it in GitHub Desktop.
Save jamesona/a6c2aee53ffbdffd5cbd to your computer and use it in GitHub Desktop.
/*
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');
this.modalContainer.id = 'modal-container';
this.modalBox = document.createElement('div');
this.modalBox.id = '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.modalTitle.appendChild(this.modalClose);
this.modalBody = document.createElement('div');
if (typeof(body) === 'object') {
this.modalBody.innerHTML = body.outerHTML;
} else if (typeof(body) === 'string'){
this.modalBody.innerHTML = body;
}
this.modalContainer.appendChild(this.modalBox);
this.modalBox.appendChild(this.modalTitle);
this.modalBox.appendChild(this.modalBody);
this.destroy = function(){
this.modalBox.parentNode.removeChild(this.modalBox);
};
this.attach = function(ele){
var self = this;
(ele) ? ele.appendChild(this.modalBox) : document.body.appendChild(this.modalBox);
(function(){
self.modalClose.addEventListener('click', function(){
self.destroy()
});
})();
};
(callback) ? callback() : null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment