65.9K
CodeProject is changing. Read more.
Home

jQuery Extension Function to Center an Element to Window

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

Mar 29, 2015

CPOL
viewsIcon

5350

Extends the jQuery object, adding a function to center the selected element to the window

Using the Code

Add this code to your JavaScript file to extend jQuery with the new function.

$.fn.centerToWindow = function()
{
    $(this).offset({
        top: ($(window).height() / 2) - ($(this).height() / 2),
        left: ($(window).width() / 2) - ($(this).width() / 2)
    });
    return $(this);
};

To use the function, use the jQuery object to select one or more elements and use the resulting object to call the function.

$('#myElement').centerToWindow();