Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

jQuery Extension Function to Center an Element to Window

5.00/5 (7 votes)
29 Mar 2015CPOL 5.4K  
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.

JavaScript
$.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.

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)