Skip to content

Instantly share code, notes, and snippets.

@blvdmitry
Created October 21, 2019 19:31
Show Gist options
  • Save blvdmitry/89fa133bf42c9c3ea80b2556201065fc to your computer and use it in GitHub Desktop.
Save blvdmitry/89fa133bf42c9c3ea80b2556201065fc to your computer and use it in GitHub Desktop.
export const isRTL = () => !!document.querySelector('[dir=rtl]');
export const isLTR = () => !isRTL();
let cachedScrollType;
const getScrollType = () => {
if (cachedScrollType) return cachedScrollType;
const dummy = window.document.createElement('div');
dummy.appendChild(document.createTextNode('DUMMY'));
dummy.dir = 'rtl';
dummy.style.width = '4px';
dummy.style.height = '1px';
dummy.style.position = 'absolute';
dummy.style.top = '-1000px';
dummy.style.overflow = 'scroll';
document.body.appendChild(dummy);
// IE
cachedScrollType = 'reverse';
// Webkit
if (dummy.scrollLeft > 0) {
cachedScrollType = 'default';
// FF + Opera
} else {
dummy.scrollLeft = 1;
if (dummy.scrollLeft === 0) {
cachedScrollType = 'negative';
}
}
document.body.removeChild(dummy);
return cachedScrollType;
};
function mirrorScrollLeft(el, value) {
const rtl = isRTL();
if (!rtl) return value;
const scrollType = getScrollType();
if (scrollType === 'negative') return -value;
if (scrollType === 'reverse') return value;
return el.scrollWidth - el.clientWidth - value;
}
// Return normalized scroll value which simulates scrollRight for RTL
// Scroll by 20px from the left side in LTR, returns 20
// Scroll by 20px from the right side in RTL, returns 20
export const normalizeScrollLeft = (el) => mirrorScrollLeft(el, el.scrollLeft);
// Takes simulated scrollRight value and denormalizes it back to browser behavior
export const denormalizeScrollLeft = mirrorScrollLeft;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment