I have developed a Snap-to-Component Directive that functions perfectly in Firefox but encounters issues in Chrome. I have checked canIUse and it should be compatible, so I am seeking insights, especially regarding cross-browser compatibility. Your input is highly appreciated. Thank you.
Directive code snippet (windowsnap.directive.ts):
import {Directive, Input, HostListener, ElementRef} from '@angular/core';
@Directive({
selector: '[windowsnap]'
})
export class WindowSnapDirective {
scrollHistory = [];
parent = this.el.nativeElement;
constructor(private el: ElementRef) { }
closest(num, arr) {
let curr = arr[0];
arr.forEach((val) => {
if (Math.abs(num - val) < Math.abs(num - curr)) {
curr = val;
}
});
return curr;
}
@HostListener('mouseup') onMouseUp(){
this.scrollHistory.unshift(this.parent.scrollLeft);
if(this.parent.scrollLeft === this.scrollHistory[1]) { return; }
console.log(this.scrollHistory);
let child1El = this.parent.querySelector('child1');
let child2El = this.parent.querySelector('child2');
let child3El = this.parent.querySelector('child3');
let child1LeftBoundary = child1El.offsetLeft;
let child1MiddleBoundary = child1El.offsetWidth * 0.5 + child1LeftBoundary;
let child1RightBoundary = child1El.offsetWidth + child1LeftBoundary;
let child2LeftBoundary = child2El.offsetLeft;
let child2MiddleBoundary = child2El.offsetWidth * 0.5 + child2LeftBoundary;
let child2RightBoundary = child2El.offsetWidth + child2LeftBoundary;
let child3LeftBoundary = child3El.offsetLeft;
let child3MiddleBoundary = child3El.offsetWidth * 0.5 + child3LeftBoundary;
let child3RightBoundary = child3El.offsetWidth + child3LeftBoundary;
let viewBoxL = this.parent.scrollLeft;
let viewBoxC = this.parent.scrollLeft + (this.parent.offsetWidth * 0.5);
let viewBoxR = this.parent.scrollLeft + this.parent.offsetWidth;
let a = (viewBoxC - child1MiddleBoundary);
let b = (viewBoxC - child2MiddleBoundary);
let c = (viewBoxC - child3MiddleBoundary);
let closestChildMid = this.closest(0, [a, b, c]);
if(closestChildMid === a) {
child1El.scrollIntoView({behavior: "smooth", block: "center"});
}
if(closestChildMid === b) {
child2El.scrollIntoView({behavior: "smooth", block: "center"});
}
if(closestChildMid === c) {
child3El.scrollIntoView({behavior: "smooth", block: "center"});
}
}
}
Any assistance is valued. Thank you!