Skip to content

Instantly share code, notes, and snippets.

@TravisMullen
Last active February 21, 2016 01:45
Show Gist options
  • Save TravisMullen/5f907a8805ffac8b1541 to your computer and use it in GitHub Desktop.
Save TravisMullen/5f907a8805ffac8b1541 to your computer and use it in GitHub Desktop.
Fixing Elements to Page
angular.module( 'YOUR_APP.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();
});
}
};
} ]
);
@TravisMullen
Copy link
Author

Uses: https://github.com/TravisMullen/responsive-javascript

 $win.on('scroll viewport:not:small:resize', function() {
                    setElementPosition();
                });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment