centerinclient.js 1.9 KB

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