Skip to main content

A small jQuery plugin I wrote for centering elements. It also detects screen size changes (or resize) and repositions the element accordingly.

(function ($) {
  /**
   * jQuery center element.
   *
   * @example
   *   $("selector").center(true);
   *
   * @author Jon LaBelle
   * @param  {bool}   centerVertical Center the element vertically.
   * @return {object} The jQuery object.
   */
  jQuery.fn.center = function (centerVertical) {

    var $element = $(this);
    var resizeTimeout, $win = $(window);

    var centerElement = function () {
      $element.css("position", "absolute");
      if (centerVertical === true) {
        $element.css("top", (($win.height() - $element.outerHeight()) / 2));
      }
      $element.css("left", (($win.width() - $element.outerWidth()) / 2));
    };

    $element.on('centerElement', centerElement).trigger('centerElement');

    $win.on('resize', function () {
      if (resizeTimeout) {
        clearTimeout(resizeTimeout);
      }
      resizeTimeout = setTimeout(function () {
        $element.trigger('centerElement');
      }, 100);
    });

    return $element;
  };
  
})(jQuery);