Display Centered Window


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. function getScrollXY() {
  2. var scrOfX = 0, scrOfY = 0;
  3. if( typeof( window.pageYOffset ) == 'number' ) {
  4. //Netscape compliant
  5. scrOfY = window.pageYOffset;
  6. scrOfX = window.pageXOffset;
  7. } else if( document.body && ( document.body.scrollLeft | document.body.scrollTop ) ) {
  8. //DOM compliant
  9. scrOfY = document.body.scrollTop;
  10. scrOfX = document.body.scrollLeft;
  11. } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
  12. //IE6 standards compliant mode
  13. scrOfY = document.documentElement.scrollTop;
  14. scrOfX = document.documentElement.scrollLeft;
  15. }
  16. return [ scrOfX, scrOfY ];
  17. }
  18. function getWindowSize() {
  19. var myWidth = 0, myHeight = 0;
  20. if( typeof( window.innerWidth ) == 'number' ) {
  21. //Non-IE
  22. myWidth = window.innerWidth;
  23. myHeight = window.innerHeight;
  24. } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
  25. //IE 6+ in 'standards compliant mode'
  26. myWidth = document.documentElement.clientWidth;
  27. myHeight = document.documentElement.clientHeight;
  28. } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
  29. //IE 4 compatible
  30. myWidth = document.body.clientWidth;
  31. myHeight = document.body.clientHeight;
  32. }
  33. return [ myWidth, myHeight ];
  34. }
  35. function DisplayCenteredWindow(el, width, height) {
  36. var x = getScrollXY()[0];
  37. var y = getScrollXY()[1];
  38. var halfWidth = width/2;
  39. var halfHeight = height/2;
  40. //var offsetX = 250 + x;
  41. //var offsetY = 100 + y;
  42. var sizeX = getWindowSize()[0];
  43. var sizeY = getWindowSize()[1];
  44. var cssLeft, cssTop;
  45. cssLeft = Math.ceil(sizeX / 2) - halfWidth + x;
  46. cssTop = Math.ceil(sizeY / 2) - halfHeight + y;
  47. $(el).css({position:'absolute', top:cssTop+'px', left:cssLeft+'px'});
  48. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.