que1326
que1326

Reputation: 2325

How to make a sticky header in Angular Js?

I am trying to achieve an AngularJs sticky header concept using only angular or vanilla javascript. (no jQuery dependency). I tried to create this directive, but I am missing something ... some suggestions please ?

Working updated code

JavaScript

angular.module('app', [])
.directive('stickyHeader', function ($window) {
return {
    restrict: 'AE',
    link: function (scope, element, attrs) {
      var header = angular.element(element);
      var clone = header[0].before(header.clone().addClass("clone"));

      angular.element($window).bind("scroll", function () {
        var fromTop = $window.pageYOffset;
        var body = angular.element(document).find('body');
        body.toggleClass('down', (fromTop > 400));
      });

      console.log('$window', $window);
      console.log('element', element);
      console.log('header', header);
  }
};
})
 .controller('Main', function ($scope) {
  $scope.angular = angular;
});

Upvotes: 0

Views: 5002

Answers (4)

Naseeruddin V N
Naseeruddin V N

Reputation: 625

<div>above content</div>
<div style="position: sticky;top: 0px;z-index: 1;background-color: red">header</div>
<div style="height: 200px">content-1</div>
<div>content-2</div>

try adding the following code.

style="position: sticky;top: 0px;z-index: 1;

Upvotes: 4

que1326
que1326

Reputation: 2325

The problem was that var clone = undefined, so I've changed it to:

var clone = header.prepend(header.clone().addClass('clone'), header);

This way I can find the clone position so that I can toggle the class based on the condition: pixelsFromTopScreen > clonePixelsPositionFromTop

Upvotes: 0

rachmatsasongko
rachmatsasongko

Reputation: 186

I tried to edit your pen and this is what i can do EDITED PEN

What I did is added this lines

  if (fromTop >= 80) {
    angular.element(header[0]).css("top", '0');
    angular.element(header[0]).css("position", 'fixed');
  } else {
    angular.element(header[0]).css("top", '');
    angular.element(header[0]).css("position", '');
  }

Upvotes: 0

Paul Roefs
Paul Roefs

Reputation: 468

Try giving it position fixed after (fromTop > 400).
With your code I would say add this to your css.

.down header {
  position:fixed;
  top:0px;
}

EDIT: I noticed fromTop > 400 is a bit too much for it, try using fromTop > 100

Upvotes: 0

Related Questions