Click here to Skip to main content
15,887,422 members
Articles / Web Development / HTML
Tip/Trick

jQuery Extension Function to Center an Element to Window

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
29 Mar 2015CPOL 5.2K   4  
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)


Written By
Web Developer JBHworks
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --