redoc/lib/common/components/StickySidebar/sticky-sidebar.js

64 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-12-26 20:44:39 +03:00
'use strict';
2016-01-21 01:09:42 +03:00
import {Directive, ElementRef} from 'angular2/core';
2015-12-26 20:44:39 +03:00
import {BrowserDomAdapter} from 'angular2/platform/browser';
2016-01-21 01:09:42 +03:00
@Directive({
selector: '[sticky-sidebar]',
2015-12-27 00:12:10 +03:00
inputs: ['scrollParent', 'scrollYOffset']
2015-12-26 20:44:39 +03:00
})
export default class StickySidebar {
2016-01-21 01:09:42 +03:00
constructor(elementRef, dom) {
2015-12-26 20:44:39 +03:00
this.element = elementRef.nativeElement;
2016-01-21 01:09:42 +03:00
this.dom = dom;
2015-12-26 20:44:39 +03:00
// initial styling
2016-01-21 01:09:42 +03:00
this.dom.setStyle(this.element, 'position', 'absolute');
this.dom.setStyle(this.element, 'top', '0');
this.dom.setStyle(this.element, 'bottom', '0');
this.dom.setStyle(this.element, 'max-height', '100%');
2015-12-26 20:44:39 +03:00
}
bind() {
2016-01-21 01:09:42 +03:00
this.cancelScrollBinding = this.dom.onAndCancel(this.scrollParent, 'scroll', () => { this.updatePosition(); });
2015-12-26 20:44:39 +03:00
this.updatePosition();
}
unbind() {
this.cancelScrollBinding && this.cancelScrollBinding();
}
updatePosition() {
if ( this.scrollY + this.scrollYOffset() >= this.redocEl.offsetTop) {
2015-12-26 20:44:39 +03:00
this.stick();
} else {
this.unstick();
}
}
stick() {
2016-01-21 01:09:42 +03:00
this.dom.setStyle(this.element, 'position', 'fixed');
this.dom.setStyle(this.element, 'top', this.scrollYOffset() + 'px');
2015-12-26 20:44:39 +03:00
}
unstick() {
2016-01-21 01:09:42 +03:00
this.dom.setStyle(this.element, 'position', 'absolute');
this.dom.setStyle(this.element, 'top', 0);
2015-12-26 20:44:39 +03:00
}
get scrollY() {
return (this.scrollParent.pageYOffset != null) ? this.scrollParent.pageYOffset : this.scrollParent.scrollTop;
2015-12-26 20:44:39 +03:00
}
ngOnInit() {
this.redocEl = this.element.offsetParent;
this.bind();
}
ngOnDestroy() {
this.unbind();
}
}
StickySidebar.parameters = [ [ElementRef], [BrowserDomAdapter] ];