Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (function ( $ ) {
- /**
- * A jQuery plugin that will position an element relative to another element, regardles of whether or not they share the
- * same parent in the DOM.
- *
- * Note: This must be called within a $(document).ready() call to work properly. If loading images in the element
- * that aren't specifically sized via CSS, it may be necessary to call this within a $(window).load() call
- * depending on the positioning used.
- *
- * @param $el The element off of which relative positioning should be based.
- * @param top Defines top positioning, which can be a number, percentage or 'centerline'.
- * @param left Defines left positioning, which can be a number, percentage or 'centerline'.
- * @returns {*} Returns the original element so that chaining works properly.
- */
- $.fn.positionRelativeTo = function ( $el, top, left ) {
- var isPct = function ( value ) {
- return isNaN(value) ? '%' === value.substr(- 1) : false;
- };
- var convertPercentageToDecimal = function ( percentage ) {
- var num = isNaN(percentage) ? percentage.replace('%', '') : percentage;
- return isNaN(num) ? 0 : parseInt(num, 10) / 100;
- };
- var getPosition = function ( $this ) {
- var position = { top: 0, left: 0 };
- // Top
- if ( typeof top === 'undefined' ) {
- position.top = $el.offset().top;
- } else if ( ! isNaN(top) ) {
- position.top = $el.offset().top + parseInt(top, 10);
- } else if ( isPct(top) ) {
- position.top = $el.offset().top + ( $el.outerHeight() * convertPercentageToDecimal(top) );
- } else if ( 'centerline' === top ) {
- position.top = Math.round(( $el.offset().top + ( $el.outerHeight() / 2 ) ) - ( $this.outerHeight() / 2 ));
- }
- // Left
- if ( typeof left === 'undefined' ) {
- position.left = $el.offset().left;
- } else if ( ! isNaN(left) ) {
- position.left = $el.offset().left + parseInt(left, 10);
- } else if ( isPct(left) ) {
- position.left = $el.offset().left + ( $el.outerWidth() * convertPercentageToDecimal(left) );
- } else if ( 'centerline' === left ) {
- position.left = Math.round(( $el.offset().left + ( $el.outerWidth() / 2 ) ) - ( $this.outerWidth() / 2 ));
- }
- return position;
- };
- return this.each(function () {
- if ( 1 === $el.length ) {
- var $self = $(this);
- $self.detach().appendTo('body').css('position', 'absolute');
- $self.offset(getPosition($self));
- $(window).resize(function () {
- $self.offset(getPosition($self));
- });
- }
- });
- };
- })(jQuery);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement