1 заметка с тегом

rtl

RTL layout cross-browser element.scrollLeft issue solution

1 марта 2017, 16:42

Sometimes there is a moment as you make horizontal scrolling slider or timeline and become aware of the real world around you.

Some people will figure out the difference in how browsers implements Element.scrollLeft property on right to left layout (dir=«rtl»).

Most browsers have an initial value of scrollLeft equal to zero and will increase its value as you scroll (IE/Edge).

But in Chrome initial value of scrollLeft depends on scroll width (!) and is reduced to zero as you scroll.

Next problem is that some browsers increase scrollLeft value (Chrome, IE/Edge) while others decrease it to make it negative (Safari and Firefox).

Here is simple and obvious solution

// get initial value
var initial = el.scrollLeft();
// try to scroll with negative value
el.scrollLeft(-1);
// check if browser sets scrollLeft to negative
if ( el.scrollLeft() < 0 ) {
    // Safari, FF
    el.scrollLeft(/* ...  */);
} else {
    if ( initial > 0 ){
        // Chrome
        el.scrollLeft(/* ...  */);
    } else {
        // IE
        el.scrollLeft(/* ...  */);
    }
}