Search code examples
javascriptdompositioningdom-manipulation

Position a dialog box in center of viewable region of a browser window using javascript/DOM


I need to position a dialog box(read div) in the center of viewable region of a browser window. I need to use javascript DOM for doing this - making use of scrollHeight, scrollTop, clientHeight, etc. is permissible. The dialog box needs to appear upon clicking a link, it remains invisible otherwise.

CAN'T USE JQUERY TO CREATE A MODAL DIALOG.

Can somebody help me with the centering part of this problem

Regards


Solution

  • (function () {
      var getVieportWidth,
          getViewportHeight;
    
      if (window.innerWidth) {
        // All browsers except IE
        getViewportWidth = function() { return window.innerWidth; };
        getViewportHeight = function() { return window.innerHeight; };
      }
      else if (document.documentElement && document.documentElement.clientWidth) {
        // IE6 with DOCTYPE
        getViewportWidth = function() { return document.documentElement.clientWidth; };
        getViewportHeight = function() { return document.documentElement.clientHeight; };
      }
      else if (document.body.clientWidth) {
        // IE4, IE5, IE6 without DOCTYPE
        getViewportWidth = function() { return document.body.clientWidth; };
        getViewportHeight = function() { return document.body.clientHeight; };
      }
    
      var dialogDIVNode = document.getElementById('someID'),
          dialogDIVNodeWidth = dialogDIVNode.offsetWidth,
          dialogDIVNodeHeight = dialogDIVNode.offsetHeight;
    
      document.getElementById('someLinkID').addEventListener('click', function (e) {
        e.preventDefault();
    
        dialogDIVNode.style.left = ( getViewportWidth() / 2 - dialogDIVNodeWidth / 2 ) + 'px';
        dialogDIVNode.style.top = ( getViewportHeight() / 2 - dialogDIVNodeHeight / 2) + 'px';
        dialogDIVNode.style.display = 'block';
      }, false);
    }());