1
0
mirror of https://github.com/MontFerret/ferret.git synced 2025-11-06 08:39:09 +02:00

Added a check whether an element is in the viewport before scrolling (#342)

This commit is contained in:
Tim Voronov
2019-07-26 15:34:18 -04:00
committed by GitHub
parent b323a984cc
commit 843bc2a44e

View File

@@ -6,6 +6,19 @@ import (
) )
const ( const (
isElementInViewportTemplate = `
function isInViewport(elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
`
scrollTopTemplate = ` scrollTopTemplate = `
window.scrollTo({ window.scrollTo({
left: 0, left: 0,
@@ -24,9 +37,14 @@ const (
scrollIntoViewTemplate = ` scrollIntoViewTemplate = `
(el) => { (el) => {
el.scrollIntoView({ ` + isElementInViewportTemplate + `
behavior: 'instant'
});
if (!isInViewport(el)) {
el.scrollIntoView({
behavior: 'instant'
});
}
return true; return true;
} }
@@ -59,10 +77,14 @@ func ScrollIntoViewBySelector(selector string) string {
throw new Error('%s'); throw new Error('%s');
} }
el.scrollIntoView({ %s
behavior: 'instant'
}); if (!isInViewport(el)) {
el.scrollIntoView({
behavior: 'instant'
});
}
return true; return true;
`, selector, drivers.ErrNotFound) `, selector, drivers.ErrNotFound, isElementInViewportTemplate)
} }