@nydelic/toolbox
Version:
A collection of hooks, components, and other helpful tools.
70 lines • 2.64 kB
JavaScript
;
// go-light: simple and lightweight methods thought to be used in place of frameworks or libraries who solve this
Object.defineProperty(exports, "__esModule", { value: true });
exports.scrollTo = exports.checkIE = void 0;
function checkIE() {
const ua = window.navigator.userAgent;
const msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv:11\./)) {
return true;
}
return false;
}
exports.checkIE = checkIE;
function easingMethod(t, // t = current time
b, // b = start value
c, // c = change in value
d, // d = duration;
method) {
if (method === "easeInOutQuad") {
t /= d / 2;
if (t < 1)
return (c / 2) * t * t + b;
t--;
return (-c / 2) * (t * (t - 2) - 1) + b;
}
// linear
return (c / d) * t;
}
/** scroll a dom element programatically by n distance in t time (exact time or a relative time to the distance) */
function scrollTo({ top, left, duration, element: elementArg, easing = "linear", callback, nonblocking, }) {
// default to document scrollingElement if no element was provided
const element = elementArg || document.scrollingElement || document.documentElement;
function genericScroll(amount, direction) {
let trackPreviousScrollPos = element[direction];
// set-up values
const scrollDuration = "exact" in duration ? duration.exact : duration.relative * amount;
const start = element[direction];
const change = amount - start;
const startDate = +new Date();
// transformation for each frame
function animateScroll() {
if (nonblocking && trackPreviousScrollPos !== element[direction]) {
return;
}
const currentDate = +new Date();
const currentTime = currentDate - startDate;
element[direction] = easingMethod(currentTime, start, change, scrollDuration, easing);
if (currentTime < scrollDuration) {
trackPreviousScrollPos = element[direction];
requestAnimationFrame(animateScroll);
}
else {
// animation finished
element[direction] = amount;
callback === null || callback === void 0 ? void 0 : callback(direction === "scrollTop" ? "top" : "left");
}
}
animateScroll();
}
// scroll Y
if (top) {
genericScroll(top, "scrollTop");
}
// scroll X
if (left) {
genericScroll(left, "scrollLeft");
}
}
exports.scrollTo = scrollTo;
//# sourceMappingURL=go-light.js.map