EasyDialogBox

Easy to use Javascript dialog box, messagebox, alert, confirm, prompt, toast.

Plain vanilla Javascript, no libraries.

Customizable, responsive, draggable, resizable, lightweight.

Using standard Javascript (ES5), HTML and CSS.
Crossbrowser, legacy browser support as much as possible.

https://github.com/keejelo/EasyDialogBox

 

 

HOW TO ?

Include the CSS and Javascript files between <head> and </head> as you would normally do in a HTML file:

<!DOCTYPE html> <html> <head> <meta charset="utf-8" />   <link type="text/css" rel="stylesheet" href="css/easydlg.css" />   <script src="js/easydlg.min.js" charset="utf-8"></script>    

Then it can be used like the examples below. Boxes can also be created with pre-written HTML.

All dialogboxes are modal by default, but this can be changed among other things, by using optional flags.
Displaying multiple boxes at the same time is also possible, or how about a Toast!

The base module (object)

 EasyDialogBox 

As long as the script-file is included as above then the module will be initialized automatically when page loads, after that all the functions and methods are available.

 

Create dialog

Minimum syntax:
let myObj = EasyDialogBox.create(id, strBoxTypeClass, strTitle, strMessage);

Full syntax:
let myObj = EasyDialogBox.create(id, strBoxTypeClass, strTitle, strMessage, fnCallback, x, y, w, h);

Return value = object, or null if could not be created.

 

Parameters:

id = custom id 'string' , if not used then you must set it to a false, null or 0 (zero)

 

strBoxTypeClass = can be any of the strings in the table below, by itself or combined with others separated by a space:
DialogtypeDescription
dlgDefault dialog with Close button.
dlg-closeDialog with Close button, add Close button to dialog.
dlg-promptDialog with an inputfield, OK + Cancel buttons.
dlg-yesDialog with Yes button, add Yes button to dialog.
dlg-noDialog with No button, add No button to dialog.
dlg-yes-noDialog with Yes + No buttons, add Yes + No buttons to dialog.
dlg-okDialog with OK button, add OK button to dialog.
dlg-cancelDialog with Cancel button, add Cancel button to dialog.
dlg-ok-cancelDialog with OK + Cancel buttons, add OK + Cancel buttons to dialog.
dlg-toast Toast dialogbox, shorthand that combines the flags below:
dlg dlg-disable-heading dlg-disable-footer dlg-disable-drag dlg-disable-overlay
 
Optional flags 1Description
dlg-disable-headingDialog without heading.
dlg-disable-footerDialog without footer.
dlg-disable-btnsDialog without any buttons in the footer.
dlg-disable-dragDisable drag'n'drop, dialogbox cannot be moved by dragging its heading.
dlg-disable-escDisable Esc-key so it won't close the box.
dlg-disable-clickoutDisable the ability to click outside the box to close it.
dlg-disable-overlayDisable translucent overlay/background color and makes the dialogbox modeless.
 
dlg-nomodalSame as dlg-disable-overlay
dlg-multi Makes it possible and easier to use multiple dialogboxes at the same time.
Shorthand that combines the flags below:
dlg-disable-overlay dlg-disable-esc dlg-disable-clickout
Note: IE 8/9/10 - to switch between dialogs you have to click on some text or visible element.
dlg-resizeMakes the dialogbox resizable, adds a small resize-handle on the bottom-right side.
 
dlg-infoDisplay information icon on the left inside box.
dlg-questionDisplay question icon on the left inside box.
dlg-errorDisplay error icon on the left inside box.
dlg-successDisplay success icon on the left inside box.
dlg-exclamationDisplay exclamation icon on the left inside box.
 
dlg-roundedAdd rounded corners to box.
dlg-shadowAdd shadow behind box.
dlg-fadeDialogbox fades in when shown, not when closed, only fades out if used with timed hiding

1. must be used in combination with a dialogtype, separated by a space.

 

strTitle = title text of the box, text only recommended, but can contain HTML.

 

strMessage = HTML content to custom and build as you wish, images, forms, anything you want, or just plain text.

 

Optional parameters:

fnCallback = callback function that executes when box closes (or you can just use myObj.onClose() function instead)

If using full syntax, but not using the fnCallback parameter, then you must set it to a false, null or 0 (zero)

 

x = initial horizontal position of the box. If not used then you can set it to null and it defaults to horizontal center in viewport.

y = initial vertical position of the box. If not used then you can set it to null and it defaults to vertical center in viewport.

w = initial width of the box. If not used then you can set it to null and it defaults to 600px as defined in the css-file.

h = initial height of the box. If not used then you can set it to null and the height is adjusted by content.

Note: Use of x, y, w, h can possibly break the dialogbox "responsiveness".

 

 

Properties of a created object

NameTypeDescription
idstringdialogbox ID
strTypeClassstringdialogbox type
strTitlestringdialogbox heading title
strMessagestringdialogbox contents (text and HTML)
callback()methodcustom function that fires when dialog is closed (works the same way as onClose/onHide)
xnumberdialogbox horizontal position
ynumberdialogbox vertical position
wnumberdialogbox width
hnumberdialogbox height
strInputstringreturned string value from user input when using dlg-prompt
nRetCodenumberreturns the value of the dialog-button the user clicked
bVisiblebooleanvariable that indicates if dialog is visible or not
bExistInDOMbooleanvariable that indicates if dialog exist in DOM
bFadebooleanvariable that indicates if dialog should fade. Using dlg-fade sets this to true
nTimeIdnumbervariable that holds the timeout ID when using timed hiding
show()methodshows dialog
hide()methodhides dialog
destroy()methoddestroys dialog
onCreate()methodfires when dialog is created
onShow()methodfires when dialog is shown
onHide()methodfires when dialog is hidden/closed
onClose()methodfires when dialog is closed
onDestroy()methodfires when dialog is destroyed
elelementreference to dialogbox element itself
$()methodget elements inside dialog
width()methodset dialogbox width (px)
height()methodset dialogbox height (px)
xPos()methodchange dialogbox X position (pixels from left)
yPos()methodchange dialogbox Y position (pixels from top)
center()methodposition dialogbox in center of window/viewport
colorBorder()methodset dialog bordercolor
colorHeading()methodset dialog heading backgroundcolor
color()methodshorthand, set both heading and border same color
addButton()methodadd custom button to dialog footer

 

 

 

 

Show dialog

myObj.show();

Return value = the object itself if the box could be shown, false if not.

 

 

Hide dialog (close)

Default use is without any parameters: myObj.hide();, use this if you just want to hide right away without any more fuzz.

Return value = the object itself

(Pressing the keyboard escape-key Esc also fires this function)

Optional parameters:

Else you can use it with paramters like this: myObj.hide(msec); or this myObj.hide(msec, skip); if using both.

msec is a value in milliseconds of type number, to delay the hiding/closing of the dialogbox.
The timeout ID is stored in variable myObj.nTimeId so it can be used with clearTimeout(nTimeId); or some other custom codestuff.

skip is a value of type boolean, to skip execution of the objects .onHide() function. Only skips if value is true boolean, using true, else it executes as normal which is also default.

 

 

Destroy dialog

myObj.destroy();

Return value = true if object was deleted, false if not.

All dialogboxes will be kept in the DOM by default once created, they are only removed from the DOM when the user executes the "destroy" function.
The user is responsible for deleting/destroying the dialogbox objects to prevent DOM-fill and "memory leaks".

Tip: By specifying an ID when creating a box, the existing box are reused when hiding and showing, instead of a new box being created each time the box is hidden and shown, filling up the DOM and leak memory if not destroyed.

It's good practice to destroy a dialogbox when it's not going to be used again and no longer needs to exist in DOM.

The simplest way to do this is in the functions myObj.onClose() or myObj.onHide().

Like this myObj.onClose = myObj.destroy; if nothing else is going on in the "onClose" function.

If you need to do other stuff in that function also, then you can do something like below:

  myObj.onClose = function() { // .. other stuff ..   myObj.destroy(); };  

 

 

 

Get the dialogbox HTML element itself

myObj.el;

Return value = HTMLElement

 

 

Get HTML elements inside the dialogbox

There are multiple ways to do this, all which are similar to querySelectorAll()

myObj.$(); using () blank, returns the dialogbox HTML element itself, same as myObj.el;, using querySelector()

myObj.$('#someId'); using # (hash), returns a single HTML element containing the specified ID, using querySelector(), or null if none exist in DOM.

myObj.$('.someClass'); using . (period), returns a NodeList, or null if none exist in DOM.

myObj.$('someElement'); returns a NodeList, or null if none exist in DOM.

You can also mix it up e.g.:

myObj.$('#someID p input.myFormData'); returns a NodeList, or null if none exist in DOM.

myObj.$('#someID p input.myFormData')[0]; returns the first HTML element in a NodeList indexed [0]

NOTE: In all instances you can check against null to see if any elements were found.

 

 

Set dialog width

myObj.width(value);

Where value is a pixel value of type number, e.g. myObj.width(400);
Return value = the object itself

 

 

Set dialog height

myObj.height(value);

Where value is a pixel value of type number, e.g. myObj.height(600);
Return value = the object itself

 

 

Change dialog X position

myObj.xPos(value);

Where value is a pixel value of type number, e.g. myObj.xPos(200);

Return value = the object itself

 

 

Change dialog Y position

myObj.yPos(value);

Where value is a pixel value of type number, e.g. myObj.yPos(300);

Return value = the object itself

 

 

Center dialog in window

myObj.center();

Positions the dialog in horizontal and vertical center of window or viewport.

Return value = the object itself

 

 

Change colors

You can set the colors of the dialogs border and heading for some basic UI-theming without editing the CSS file or other custom CSS stuff.

myObj.color('#990000'); , to set both the heading and border color to same color.

Or you can set them individually like below:

myObj.colorBorder('#990000'); , to set the border color to one color.

myObj.colorHeading('#005599'); , to set the heading backgroundcolor to another color.

Any CSS color value will work.

To remove the custom color and go back to default you can just change the custom color value to an empty string ''

For instance from myObj.colorBorder('#ff0000'); to this myObj.colorBorder(''); , to return color back to default defined in CSS file.

Return value = the object itself

 

 

Add custom button to footer

With this method you can add your own custom buttons to the footer of the dialog.

Syntax: myObj.addButton(strText, fnClick, nPos);

Where strText is of type string, the text that you want to display on the button.

fnClick is of type function, the click-event function for the button. Can either be a reference to a function or a function written inline.

nPos is of type number, and is the index position of where you want to insert the button among the rest of the footer-buttons.
If set to 0 then it's inserted as the first button on the left side, if set to 1 then it's inserted as the second button from the left side, 2 as third button etc.
If omitted/not specified then the button is just appended last on the right side.

Return value = the button HTMLElement itself

  // ** Example, add a custom button to the footer, as first button on the left (index 0) let myBtn = myObj.addButton('My new button', function() { console.log('My new button was clicked'); }, 0);   // ** Set the new buttons' font to bold (or do something with myBtn) myBtn.style.fontWeight = 'bold';    

 

 

 

Object event-methods

 

myObj.onCreate(); fires when dialogbox object is created.

You can write your own function if you want to do something when the event occurs:

  myObj.onCreate = function() { // .. do something here .. };  

 

 

myObj.onShow(); fires when dialogbox is about to be displayed.

You can write your own function if you want to do something when the event occurs:

  myObj.onShow = function() { // .. do something here .. };  

 

 

myObj.onHide(); fires when dialogbox is being hidden.

You can write your own function if you want to do something when the event occurs:

  myObj.onHide = function() { // .. do something here .. };  

 

 

myObj.onClose(); fires when dialogbox is closing.

You can write your own function if you want to do something when the event occurs:

  myObj.onClose = function() { // .. do something here .. };  

 

 

myObj.onDestroy(); fires when dialogbox is being destroyed.

You can write your own function if you want to do something when the event occurs:

  myObj.onDestroy = function() { // .. do something here .. };  

 

 

 

 

 

Get dialog object based on its id

Get object from id, can be used to get object from a pre-written HTML box or other created dialog objects by searching for its 'id' in the array of objects.

let myObj = EasyDialogBox.getById(id);

Return value = object or null if could not be found.

 

 

Get all dialog objects

Get all dialogbox objects that is currently stored in the object-array.

let myArray = EasyDialogBox.getAll();

Return value = array

 

 

Initialize all pre-written HTML dialogbox-objects

This is automatically done once when the script is loaded the first time. But in case there was more HTML content added later on and you need to invoke it again, you can.
It will sweep up all the boxes and activate their "click-openers".

EasyDialogBox.init();

Return value = number of pre-written HTML dialogboxes parsed.

 

 


 

 

Examples

 

Simple example

Create a dialog and then show it.

  // Javascript ...   // ** Create a new dialogbox object let myBox = EasyDialogBox.create('someId', 'dlg', 'My title', '<p>Hello there!</p>');   // ** Clean up after closing myBox.onClose = myBox.destroy;   // ** Show the newly created box myBox.show();   // ...  

 

 

Example with Yes and No button

  // Javascript ...   // ** Create a new dialogbox object let myBox = EasyDialogBox.create('someId', 'dlg-yes-no', 'My title', '<p>Hello there!</p><p>Click Yes or No button!</p>');   // ** Create a custom onClose function myBox.onClose = function() { // ** Handle user button click   if(myBox.nRetCode === 1) { // ... user clicked "Yes" button } else if(myBox.nRetCode === 2) { // ... user clicked "No" button }   // ** Delete dialogbox on close (clean up) myBox.destroy(); };   // ** Show the newly created box myBox.show();   // ...  

 

Return values

Variables: nRetCode and strInput

These are intended to be used in the myObj.callback() or myObj.onClose() function for further processing.

 

myObj.nRetCode

ValueTypeDescription
0number"Close" button, clicked outside box, clicked [X] or pressed ESC-key
1number"Yes" button clicked
2number"No" button clicked
3number"OK" button clicked
4number"Cancel" button clicked

 

myObj.strInput

ValueTypeDescription
stringstringA string of text entered in the <input> element when using class dlg-prompt

 

 

Example with multiple dialogboxes

Create three resizable dialogs and then show them, also giving them some color.

Used class flag dlg-multi to make it easier to display multiple boxes at the same time, and dlg-resize to make 2 of the boxes resizable.
Also chaining the object method execution.

  // Javascript ...   // ** Create three dialogboxes, give them some color and open them let myBox1 = EasyDialogBox.create('box1', 'dlg dlg-multi dlg-rounded dlg-shadow', 'Box 1', '<p>This is box 1, drag and drop it around!</p><p>This box is NOT resizable!</p>', null, 100, 100); myBox1.color('#aa0000').show();   let myBox2 = EasyDialogBox.create('box2', 'dlg dlg-multi dlg-rounded dlg-shadow dlg-resize', 'Box 2', '<p>This is box 2, drag and drop it around!</p><p>This box is also resizable!</p>', null, 180, 180); myBox2.color('#009955').show();   let myBox3 = EasyDialogBox.create('box3', 'dlg dlg-multi dlg-rounded dlg-shadow dlg-resize', 'Box 3', '<p>This is box 3, drag and drop it around!</p><p>This box is also resizable!</p>', null, 260, 260); myBox3.color('#005599').show();   // ...  

 

 

"Toast" example

You can also make "toast" notification boxes by using the flag dlg-toast,
which is really a shorthand for the combined flags: dlg dlg-disable-heading dlg-disable-footer dlg-disable-drag dlg-disable-overlay
Using dlg-fade to make it fade in/out.

This example creates a toast, shows it and hides it after 3 seconds. Also chaining the object methods .show() and .hide().
Since not giving it an ID (just null), I'm choosing to destroy it after hiding to clean up the DOM and memory.
The second null is for the title, the third null for callback function, we don't need to use them here so just set them to null (any false will do)
Also using a null for the X position which means center horizontally, y=20 pixels down vertically, and width=500 pixels, height not set so it adjusts according to content.

  // Javascript ...   // ** Create some HTML content to be displayed let strToast = '<p class="medium bold">TOASTY! --- This will close 3 seconds after it\'s displayed!</p>';   // ** Create a new toastbox, give it some styling, show it, then hide it after 3 secs. let myToast = EasyDialogBox.create(null, 'dlg-toast dlg-fade', null, strToast, null, null, 20, 500); myToast.el.style.backgroundColor = '#ddeaff'; myToast.el.style.borderColor = '#0072b3'; myToast.onHide = myToast.destroy; myToast.show().hide(3000);   // ...  

 

 

Create a dialogbox with a custom form and submit it

  // Javascript example of how one could create a form and then submit it to a webserver.. // This function is invoked by some other event, button click etc. and then creates // a dialogbox with a form that will be submitted if user clicks "Ok" button.   let openEditForm = function(num, descr) { let htmlFormContent = '\ <form id="editForm" method="post" action="?update"> \ <p><input id="edit_num" name="edit_num" type="text" value="' + num + '" /><p> \ <p><input id="edit_descr" name="edit_descr" type="text" value="' + descr + '" /></p> \ </form>';   // ** Create a new dialogbox object let dlgBox = EasyDialogBox.create('editDlgBox', 'dlg-ok-cancel', 'Edit registration', htmlFormContent);   // ** Create a custom onClose function dlgBox.onClose = function() { // ** Handle user button click   // ** User clicked "Ok" button, submit form if(dlgBox.nRetCode === 3) { document.getElementById('editForm').submit(); } // ** User clicked "Cancel" button else if(dlgBox.nRetCode === 4) { // ... do nothing, dialog will close }   // ** Delete dialogbox on close (clean up) dlgBox.destroy(); };   // ** Show the newly created box dlgBox.show(); };  

 

 

// End of Javascript object creation and examples


// Beginning of HTML examples

Create dialog box with pre-written HTML

Create dialogboxes with HTML, no need to write any Javascript code unless you need callback() for button clicks etc.

If you just want to display a simple messagebox with some info, then you only have to write HTML.

 

Attribute values

The rel attribute value must contain the id of the box that the <button> is going to open.

( Don't have to be a <button>, it can be any element you want to use as an opener. )

Add class dlg-opener to the opening element, in this case a <button>, to make it open a box, a click-event-handler will automatically be created for it.

 

Optional data- attributes:

data-callback This attribute can be used if you want to run a callback function when dialogbox is closed (no matter which button was clicked).

data-x Custom horizontal position of the box, default is center of window.

data-y Custom vertical position of the box, default is center of window.

data-w Custom width of the dialogbox, default: 600px (maxWidth)

data-h Custom height of the box, default: adjusted by content.

 

HTML examples

The default box, with 'Close' button

Class: dlg or dlg-close

Return value: Close = 0

  <div id="myBox" class="dlg" title="Title text">   <p>This is a message, line one<br /> this is line two.</p>   </div>   <button rel="myBox" class="dlg-opener">Open</button>  

A default "error box"

Classes: dlg and dlg-error to display icon.

Return value: Close = 0

  <div id="myBoxError" class="dlg dlg-error" title="Title text">   <p>This is a message</p>   </div>   <button rel="myBoxError" class="dlg-opener">Open</button>  

A box with 'Yes' and 'No' buttons

Classes: dlg-yes-no, dlg-question to display icon, and dlg-fade to fade it in.

Return value: Yes = 1, No = 2

  <div id="myBoxYesNo" class="dlg-yes-no dlg-question dlg-fade" title="Title text" data-callback="myCallbackFunc">   <p>Create a new dialogbox on the fly ?</p>   </div>   <button rel="myBoxYesNo" class="dlg-opener">Open</button>  

A box with 'OK' and 'Cancel' buttons

Classes: dlg-ok-cancel and dlg-exclamation to display icon.

Return value: OK = 3, Cancel = 4

  <div id="myBoxOkCancel" class="dlg-ok-cancel dlg-exclamation" title="Title text" data-callback="myCallbackFunc">   <p>This is a message</p>   </div>   <button rel="myBoxOkCancel" class="dlg-opener">Open</button>  

A default promptbox with 'OK' and 'Cancel' buttons

Class: dlg-prompt

Return value: input = string, OK = 3, Cancel = 4

  <div id="myPromptBox" class="dlg-prompt" title="Title text" data-callback="myCallbackFunc">   <p>This is a message</p>   </div>   <button rel="myPromptBox" class="dlg-opener">Open</button>  

You can have several types at the same time if you want! Mix and match as you like! Crazy but possible!

Classes: dlg-prompt dlg-close dlg-yes-no dlg-ok-cancel dlg-info dlg-disable-overlay dlg-shadow dlg-rounded dlg-fade
(read more on classes)

Return value: input = string, Close = 0, Yes = 1, No = 2, OK = 3, Cancel = 4

  <div id="myCrazyBox" class="dlg-prompt dlg-close dlg-yes-no dlg-ok-cancel dlg-info dlg-disable-overlay dlg-shadow dlg-rounded dlg-fade" title="Title text" data-callback="myCallbackFunc" data-x="100" data-y="200" data-w="500" data-h="400">   <p>This is a crazy messagebox, just to demonstrate. It uses several classes at once and also uses the optional parameters for position and size: x, y, w, h</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>   </div>   <button rel="myCrazyBox" class="dlg-opener">Open</button>  

 

 

fini

keejelo, 2020-2021.
 

This is a message, line one
this is line two.

This is a message

Create a new dialogbox on the fly ?

This is a message

This is a message

This is a crazy messagebox, just to demonstrate. It uses several classes at once and also uses the optional parameters for position and size: x, y, w, h

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.