Posted By

jamalrob on 11/24/09


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

jirimelcak


Center an element in a client's window (eg. modal box)


 / Published in: jQuery
 

  1. // *********************************************
  2. // CENTER AN ELEMENT IN THE CLIENT'S WINDOW
  3. //
  4. $.fn.centerInClient = function(options) {
  5. /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
  6. /// Ideally the selected set should only match a single element.
  7. /// </summary>
  8. /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>
  9. /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow
  10. /// and attached to the body element to ensure proper absolute positioning.
  11. /// Be aware that this may cause ID hierachy for CSS styles to be affected.
  12. /// </param>
  13. /// <returns type="jQuery" />
  14. var opt = { forceAbsolute: false,
  15. container: window, // selector of element to center in
  16. completeHandler: null
  17. };
  18. $.extend(opt, options);
  19.  
  20. return this.each(function(i) {
  21. var el = $(this);
  22. var jWin = $(opt.container);
  23. var isWin = opt.container == window;
  24.  
  25. // force to the top of document to ENSURE that
  26. // document absolute positioning is available
  27. if (opt.forceAbsolute) {
  28. if (isWin)
  29. el.remove().appendTo("body");
  30. else
  31. el.remove().appendTo(jWin.get(0));
  32. }
  33.  
  34. // have to make absolute
  35. el.css("position", "absolute");
  36.  
  37. // height is off a bit so fudge it
  38. var heightFudge = isWin ? 2.0 : 1.8;
  39.  
  40. var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
  41. var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;
  42.  
  43. el.css("left", x + jWin.scrollLeft());
  44. el.css("top", y + jWin.scrollTop());
  45.  
  46. // if specified make callback and pass element
  47. if (opt.completeHandler)
  48. opt.completeHandler(this);
  49. });
  50. }
  51. // *********************************************

Report this snippet  

You need to login to post a comment.