Last active
February 21, 2016 01:45
-
-
Save TravisMullen/5f907a8805ffac8b1541 to your computer and use it in GitHub Desktop.
Fixing Elements to Page
This file contains 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( '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(); | |
}); | |
} | |
}; | |
} ] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uses: https://github.com/TravisMullen/responsive-javascript