Search code examples
javascriptrangescrollable

Can a scrollable DIV update a Range Slider?


I have a range slider that is scrolling the content in a DIV.

If you click on the scrollable area you will see that you can drag the the scrollable DIV to the left and right. However, when you do this the range is not updated. Is there a way to update the range when the DIV is manually scrolled? I have tried to get the onscroll() position to update the range with no luck.

https://jsfiddle.net/esoteric/fxtonew7/5/

//Range Slider
    var scroll = document.getElementById("scroll-range");
    var panel = document.getElementById("scrolling-container");

    var total = panel.scrollWidth - panel.offsetWidth;
    var percentage = total * (this.value / 100);
    var percentageWidth = total / 10; //10% for each +/- click

    scroll.oninput = function() {

        panel = document.getElementById("scrolling-container");
        total = panel.scrollWidth - panel.offsetWidth;
        percentage = total * (this.value / 100);
        panel.scrollLeft = percentage;
    }

    //Foward Arrow
    document.getElementById("increase").addEventListener("click",
        function() {
            scroll.stepUp(10);
            panel.scrollBy(percentageWidth, 0)
        });

    //Back Arrow
    document.getElementById("decrease").addEventListener("click",
        function() {
            scroll.stepUp(-10);
            panel.scrollBy(-percentageWidth, 0)
        });

        
    //Desktop grab and scroll
    const slider = document.getElementById("scrolling-container");
    let isDown = false;
    let startX;
    let scrollLeft;

    slider.addEventListener('mousedown', (e) => {
        isDown = true;
        slider.classList.add('active');
        startX = e.pageX - slider.offsetLeft;
        scrollLeft = slider.scrollLeft;
    });

    slider.addEventListener('mouseleave', () => {
        isDown = false;
        slider.classList.remove('active');
    });

    slider.addEventListener('mouseup', () => {
        isDown = false;
        slider.classList.remove('active');
    });

    slider.addEventListener('mousemove', (e) => {
        if (!isDown) return;
        e.preventDefault();
        const x = e.pageX - slider.offsetLeft;
        const walk = (x - startX) * 3;
        slider.scrollLeft = scrollLeft - walk;
    });

Solution

  • You need to calculate the opposite of what you do for when your drag the slider

    panel.addEventListener('scroll', (e)=>{
        total = panel.scrollWidth - panel.offsetWidth;
        percentage = panel.scrollLeft / total
        scroll.value = percentage * 100
    })
    

    updated fiddle: https://jsfiddle.net/gaby/dwvtLn4g/8/