Skip to content

Instantly share code, notes, and snippets.

@a-laughlin
Last active August 29, 2015 14:11
Show Gist options
  • Save a-laughlin/46153eb458359a13b0f8 to your computer and use it in GitHub Desktop.
Save a-laughlin/46153eb458359a13b0f8 to your computer and use it in GitHub Desktop.
Consistently Working AngularJS Sticky Menu Bar
.directive("stickyMenu", ['$window', function ($window) {
return {
restrict: 'A',
link: function(scope, $el, attrs) {
var windowTop;
var $win = angular.element($window);
var isFixed = false;
var origElemOffsetTop;
var origWidth;
var origOffsetLeft;
var $elemClone;
var origHeight;
var elemOffset;
$el.css({
zIndex:1000,
top:'0px'
});
// var origWinTop = 0;
function wrapRecheck(event) {
recheckPositions(event,$el);
}
// $el.css('position', 'static');
$win.on('load resize scroll',wrapRecheck);
scope.$on('$destroy',function () {
$win.off('load resize scroll',wrapRecheck);
$elemClone.remove();
scope.$destroy();
});
function recheckPositions (event) {
windowTop = $window.pageYOffset;
elemOffset = $el.offset();
if(origElemOffsetTop === undefined){
windowTop = 0;
origOffsetLeft = elemOffset.left;
origWidth = $el.width();
origHeight = $el.height();
origElemOffsetTop = elemOffset.top;
$elemClone = $('<div style="height:'+origHeight+'px;display:none"></div>')
$el.after($elemClone);
}
if(windowTop > origElemOffsetTop && isFixed === false){
isFixed = true;
$elemClone.css('display','block');
$el.css({
position:'fixed',
left:origOffsetLeft + 'px',
width:origWidth + 'px'
});
} else if(origElemOffsetTop > windowTop && isFixed === true){
isFixed = false;
$elemClone.css('display','none');
$el.css('position', 'static');
}
// else changes unnecessary
}
}
}
}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment