jQuery centering a DIV in browser

Hi Guys,

Even though simple to do after I did it but when I started it was an exercise to find the function that I needed to do what exactly I wanted.

Lets start with the markup that’s required for this topic.

  1. <div id="myDiv">I am centered</div>
The above DIV container can be present anywhere on a valid HTML page. Now lets add some styles to it. They are not required for this example but I thought nothing on web is completed without styles. So I styled above DIV with these CSS properties
  1. #myDiv {
  2. border: 10px solid rgba(140, 140, 82, .7);
  3. -webkit-border-radius: 8px;
  4. border-radius: 8px;
  5. z-index: 10000;
  6. height:200px;
  7. width:200px;
  8. padding:10px;
  9. font-family: "Lucida Grande", Arial, Helvetica, sans-serif;
  10. }

Now lets check what our jQuery plugin function will look like

  1. jQuery.fn.centerElement = function() {
  2. return this.each(function(){
  3. jQuery(this).css({'position':'absolute','left': ((jQuery(window).width() - jQuery(this).outerWidth()) / 2) + "px",'top':(($(window).height() - jQuery(this).outerHeight()) / 2) + "px"});
  4. });
  5. };

Above is something we will come up with very quickly. One question?

  1. What if the page scroll down or towards right.
    You will see that your DIV will move with the scroll
  2. What if you resize the window?

Here is a revised code that will have answer to above questions

  1. jQuery.fn.centerElement = function() {
  2. return this.each(function(){
  3. jQuery(this).css({'position':'fixed','left': ((jQuery(window).width() - jQuery(this).outerWidth()) / 2) + jQuery(window).scrollLeft() + "px",'top':(($(window).height() - jQuery(this).outerHeight()) / 2) + jQuery(window).scrollTop() + "px"}).trigger('resize');
  4. });
  5. };

This code will always keep your element at fixed position no matter it user scrolls or not.

To call this function on our DIV container do this

  1. jQuery(document).ready(function(){
  2. jQuery("#myDiv").centerElement();
  3. });

This all work fine.

Now lets consider this to handle the window resize event, use this code as a whole

  1. jQuery(document).ready(function(){
  2. jQuery("#myDiv").centerElement();
  3. });
  4.   var delay;
  5. jQuery(window).resize(function () {
  6. clearTimeout(delay);
  7. delay = setTimeout(function(){jQuery("#myDiv").centerElement();}, 250);
  8. });

I’ve introduced a delay in window resize event handler to make UI more responsive.

Demo

Here is a demo link for you to have a look

http://jaspreetchahal.org/examples/jquery-examples/center-div-in-window.html

 

I hope this helps

Cheers

Advertisement

 

 

 

VN:F [1.9.22_1171]
Rating: 0.0/5 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)

Speak Your Mind

*

CommentLuv badge