Created
March 15, 2018 22:14
-
-
Save TravisMullen/6b72f7c8c37c11c00812f88a248e362e to your computer and use it in GitHub Desktop.
AngularJS fixedContent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.module( 'vpower.directives' ).directive( 'fixedContent', | |
[ | |
function() { | |
'use strict'; | |
return { | |
restrict: 'A', | |
scope: { | |
fixedBelow: '=', | |
fixedPadding: '=' | |
}, | |
link: function($scope, element) { | |
var $win = $(window), | |
// resetHeight = true, | |
wrapName = 'fixed-content-wrapper', | |
wrapper = $('<div/>', { | |
'class' : wrapName | |
}); | |
// set position and add wrapper for tracking | |
element | |
.css({ position : 'relative' }) | |
.wrap( wrapper ); | |
// reset page positioning | |
// if ( $win.scrollTop() > 10 ) { | |
// $('html,body').animate( { scrollTop:0 } , 400 ); | |
// } | |
// TODO: remove CSS from JS! | |
function setElementPosition() { | |
var winTopPos = $win.scrollTop(), | |
elmOffset = element.offset(), | |
elmTopPos = elmOffset.top, | |
elmWrap = element.parent('.' + wrapName), | |
elmWrapOffset = elmWrap.offset(), | |
fixedBelowHeight = 0, | |
fixedBelowPadding = 0, | |
elmWrapPos; | |
if ( elmWrapOffset ){ | |
elmWrapPos = elmWrapOffset.top; | |
// use `ng-if` to avoid having to clear styles | |
// // if has ng-hide/hide class then stop calculating | |
// if ( element.hasClass('ng-hide') || element.hasClass('hide') ) { | |
// // reset height on elmWrap to prevent gap on page | |
// if ( elmWrap.height() !== 0 ) { elmWrap.height(0); } | |
// return; | |
// } | |
// if fixed below another element | |
if ( $scope.fixedBelow ) { | |
if ( $scope.fixedPadding ) { | |
fixedBelowPadding = $scope.fixedPadding; | |
} | |
fixedBelowHeight = $( $scope.fixedBelow ).outerHeight(); | |
elmTopPos = (winTopPos - elmWrapPos) + fixedBelowHeight + fixedBelowPadding; | |
} else { | |
elmTopPos = winTopPos - elmWrapPos; | |
} | |
// check scroll position and set elm position | |
if ( ( winTopPos + fixedBelowHeight ) <= elmWrapPos ) { | |
element.css({ | |
top : '0', | |
zIndex : '1' | |
}); | |
} else { | |
// required to offset content that flows below | |
elmWrap.css({ | |
position : 'relative', | |
border : '0', | |
padding : '0', | |
margin : '0', | |
height: element.outerHeight() | |
}); | |
element.css({ | |
top : elmTopPos, | |
zIndex : '9999' | |
}); | |
} | |
} | |
} | |
$win.on('scroll viewport:not:small:resize', function() { | |
setElementPosition(); | |
}); | |
$scope.$on('$destroy', function() { | |
$win.off('scroll'); | |
}); | |
} | |
}; | |
} ] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment