5
\$\begingroup\$

This is a simple jQuery script that I use to vertically center elements on pages. It's quite simple, but I would love to know if there is room for improvement.

(function( $ ){ $.fn.flexVerticalCenter = function( onAttribute, verticalOffset, parentSelector ) { return this.each(function() { var $this = $(this); // store the object var attribute = onAttribute || 'margin-top'; // the attribute to put the calculated value on var offset = parseInt(verticalOffset) || 0; // the number of pixels to offset the vertical alignment by var parent_selector = parentSelector || null; // a selector representing the parent to vertically center this element within // recalculate the distance to the top of the element to keep it centered var resizer = function () { var parent_height = (parent_selector) ? $this.parents(parent_selector).first().height() : $this.parent().height(); $this.css( attribute, ( ( ( parent_height - $this.height() ) / 2 ) + offset ) ); }; // Call once to set. resizer(); // Call on resize. Opera debounces their resize by default. $(window).resize(resizer); // Apply a load event to images within the element so it fires again after an image is loaded $this.find('img').load(resizer); }); }; })( jQuery ); 
\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is well written code, I don't think you will find any improvements here, congrats :) \$\endgroup\$ Commented Sep 9, 2013 at 2:38
  • \$\begingroup\$ Sorry, I didn't put the header. It's not my script. It's from github.com/PaulSpr/jQuery-Flex-Vertical-Center. I just want to learn from it. \$\endgroup\$ Commented Sep 9, 2013 at 2:44
  • \$\begingroup\$ This is good code :) \$\endgroup\$ Commented Sep 9, 2013 at 2:45

1 Answer 1

1
\$\begingroup\$

From the comments above, I think the code is ok :)

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.