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.
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
#myDiv { border: 10px solid rgba(140, 140, 82, .7); -webkit-border-radius: 8px; border-radius: 8px; z-index: 10000; height:200px; width:200px; padding:10px; font-family: "Lucida Grande", Arial, Helvetica, sans-serif; }
Now lets check what our jQuery plugin function will look like
jQuery.fn.centerElement = function() { return this.each(function(){ jQuery(this).css({'position':'absolute','left': ((jQuery(window).width() - jQuery(this).outerWidth()) / 2) + "px",'top':(($(window).height() - jQuery(this).outerHeight()) / 2) + "px"}); }); };
Above is something we will come up with very quickly. One question?
- What if the page scroll down or towards right.
You will see that your DIV will move with the scroll - What if you resize the window?
Here is a revised code that will have answer to above questions
jQuery.fn.centerElement = function() { return this.each(function(){ 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'); }); };
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
jQuery(document).ready(function(){ jQuery("#myDiv").centerElement(); });
This all work fine.
Now lets consider this to handle the window resize event, use this code as a whole
jQuery(document).ready(function(){ jQuery("#myDiv").centerElement(); }); var delay; jQuery(window).resize(function () { clearTimeout(delay); delay = setTimeout(function(){jQuery("#myDiv").centerElement();}, 250); });
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





JC WordPress Coupon Revealer Plugin Pro License
Australian Street Names with City, State and Display Names only, Single Server License
Recent Comments