Skip to content

Commit

Permalink
fix(directive): Fix element real offsetTop
Browse files Browse the repository at this point in the history
- Get the real offsetTop of the element in relation of the document instead of the parent element. -
When applying offset to the directive, the offsetPosition is only valid for the middle position.
  • Loading branch information
jmandreslopez committed Feb 22, 2017
1 parent d028d9e commit 7b081ea
Showing 1 changed file with 46 additions and 8 deletions.
54 changes: 46 additions & 8 deletions src/track-scroll/track-scroll.directive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class TrackScrollDirective implements OnInit {
@HostListener('document:scroll', ['$event'])
private track() {
if (!_.isUndefined(this.config) && !_.isEmpty(this.config)) {
let offsetTop = this.element.nativeElement.offsetTop;
let offsetTop = this.getCoords(this.element.nativeElement).top;
let offsetHeight = this.element.nativeElement.offsetHeight;
let offsetBottom = offsetTop + offsetHeight;

Expand Down Expand Up @@ -79,19 +79,57 @@ export class TrackScrollDirective implements OnInit {
*/
private addOffset(scrollY: number): number {
if (this.config.offset > 0) {
switch (this.config.offsetPosition) {
case 'top':
return scrollY - this.config.offset;
case 'bottom':
return scrollY + this.config.offset;
default:
break;
if (this.config.position === 'top') {
return scrollY + this.config.offset; // add offset
}
else if (this.config.position === 'bottom') {
return scrollY - this.config.offset; // minus offset
}
else if (this.config.position === 'middle') {
switch (this.config.offsetPosition) {
case 'top':
return scrollY - this.config.offset;
case 'bottom':
return scrollY + this.config.offset;
default:
break;
}
}
}

return scrollY;
}

/**
* Get the real element coordinates
*
* Thanks to @basil
* See: http://stackoverflow.com/questions/5598743/finding-elements-position-relative-to-the-document
*
* @Input el: HTMLElement
* @return { top: number, left: number }
*/
getCoords(el: HTMLElement): { top: number, left: number} {
let box = el.getBoundingClientRect();

let body = document.body;
let docEl = document.documentElement;

let scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
let scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft;

let clientTop = docEl.clientTop || body.clientTop || 0;
let clientLeft = docEl.clientLeft || body.clientLeft || 0;

let top = box.top + scrollTop - clientTop;
let left = box.left + scrollLeft - clientLeft;

return {
top: Math.round(top),
left: Math.round(left)
};
}

public ngOnInit() {
this.config = _.defaults(this.trackScrollConfig, new TrackScrollConfig());
}
Expand Down

0 comments on commit 7b081ea

Please sign in to comment.