Search code examples
javascriptjqueryhtmlcssnwjs

How can I get the right position of the scrollbar-thumbnail?


I'm trying to detect the right position of a scrollbar-thumb. Can somebody please explain if this is possible. The scrollbar thumbnail does not have fixed width. I'm using nw.js, ES6 and jQuery library.

The following is a simplified extraction of my code.

class C {
    constructor() {
        win.on('resize', this._resize.bind(this));
        $('#divId').on('scroll', this._scroll.bind(this));
    }

    _getXScrollbarThumbPos() {
        let lpos = $('#divId').scrollLeft();
        let rpos = lpos + SCROLLBAR_THUMBNAIL_WIDTH; // FIXME how can I get the scrollbarThumbnailWidth
        return rpos;
    }

    _resize() {
        let x = this._getXScrollbarThumbPos();
        //..
    }

    _scroll() {
        let x = this._getXScrollbarThumbPos();
        //..
    }
}

The resize and scroll listener work ok, the only bottleneck is how to determine the width of the scrollbar-thumbnail. win is the nw.js wrapper of the DOM's window, see here (initialization is not shown here, as it is not relevant for the question).


Solution

  • This is the solution I've eventually used. While I haven't found a way to directly obtain any dimensions of the right scrollbar-thumb position due to the dynamic width (for which I've also have not detected a way to calculate this), I have actually been able to solve the problem; By determining the width of the total content (i.e. the viewable + overflowing content), and subtracting both the viewable content width and scrolled to the left content-width, we can determine uttermost right position of the scrollable content, within the viewport, which (neglecting any possible border widths) equals the right position of the scollbar-thumb.

    class C {
        constructor() {
            win.on('resize', this._resize.bind(this));
            $('#divId').on('scroll', this._scroll.bind(this));
        }
    
        _getXScrollbarThumbPos() {
            // width of the content + overflow
            let totalWidth = $('#divId').scrollWidth;
            // width of the visible (non overflowing) content
            let viewWidth = $('#divId').width();
            // the amount of pixels that the content has been scrolled to the left
            let lpx = document.getElementById('#divId').scrollLeft;
            // the amount of pixels that are hidden to right area of the view
            let rpx = totalWidth - viewWidth - lpx;
            // represents the right position of the scrollbar-thumb
            console.log(rpx);
            return rpx;
        }
    
        _resize() {
            let x = this._getXScrollbarThumbPos();
            //..
        }
    
        _scroll() {
            let x = this._getXScrollbarThumbPos();
            //..
        }
    }