Potentially useful JavaScript for floating DIV dialogs
Wednesday, 19 October 2011 20:59 GMT | Add a comment
I am not completely new to JavaScript (previous bits here, here, and there), but this is the first time I’m having to deal with floating DIVs as dialogs. So, from my little bit of experimenting came the following. If you are after something lighter than jQuery UI, this may prove useful to you.
<!DOCTYPE html> <html> <head> <title>Dialogs Example</title> <script type="text/javascript"> if (undefined === DialogJS) { var DialogJS = (function () { var dialogs = {}; function showAsDialog(elementId, ownerElementId) { var element = document.getElementById(elementId); var ownerElement = (null !== ownerElementId) ? document.getElementById(ownerElementId) : document.documentElement; if ((null !== element) && (null !== ownerElement)) { dialogs[elementId] = { element: element, ownerElement: ownerElement }; dialogs[elementId].element.style.display = "block"; } centerDialogs(); } function hide(elementId) { if (undefined === dialogs[elementId]) { return; } dialogs[elementId].element.style.display = "none"; } function centerDialogs() { for (var x in dialogs) { centerDialog(dialogs[x]); } } function centerDialog(dialog) { if (null === dialog) { return; } var parentWidth = dialog.ownerElement.clientWidth; var parentLeft = dialog.ownerElement.offsetLeft; if (parentWidth > document.documentElement.clientWidth) { parentWidth = document.documentElement.clientWidth; parentLeft = 0; } var parentHeight = dialog.ownerElement.clientHeight; var parentTop = dialog.ownerElement.offsetTop; if (parentHeight > document.documentElement.clientHeight) { parentHeight = document.documentElement.clientHeight; parentTop = 0; } var x = 0.5 * (parentWidth - dialog.element.clientWidth) + parentLeft; var y = 0.5 * (parentHeight - dialog.element.clientHeight) + parentTop; if (x < dialog.ownerElement.offsetLeft) { x = dialog.ownerElement.offsetLeft; } if (y < dialog.ownerElement.offsetTop) { y = dialog.ownerElement.offsetTop; } dialog.element.style.position = "absolute"; dialog.element.style.left = x + "px"; dialog.element.style.top = y + "px"; } return { showAsDialog: showAsDialog, hide: hide, centerDialogs: centerDialogs }; })(); } window.onresize = DialogJS.centerDialogs; </script> </head> <body> <input type="button" value="Show Dialog" onclick="DialogJS.showAsDialog("dialog1", "page")" /> <input type="button" value="Hide Dialog" onclick="DialogJS.hide("dialog1")" /> <div id="page" style="border: 1px solid gray; height: 700px; margin: auto; width: 600px;"> THIS IS THE CONTAINER <div id="dialog1" style="background-color: antiquewhite; border: 1px solid black; display: none; height: 100px; width: 100px;"> THIS IS THE DIALOG </div> </div> </body> </html>
No Comments yet
RSS feed for comments on this post. TrackBack URI
Leave a comment
Powered by WordPress and Eddy Young.