So DOM scrollIntoView aligns top/bottom, but what about left/right?

mark picture mark · Dec 24, 2012 · Viewed 13.1k times · Source

I would like to scroll horizontally the given element. The only way I find is using ScrollIntoView DOM method, which allows either align the element's bottom with the view bottom or the top - with the view top.

But what if the element is OK with respect to the Y axis, and I only want to scroll it horizontally? How can I align its left with the view left or its right with the view right?

EDIT

Here is more context. I have a YUI table with a horizontal scrollbar. I wish to scroll it programmatically to a certain TD node. I do not think window.scrollTo is of any help to me, since the scrollbar is on a div element, not on the whole page.

EDIT2

Turns out there is a duplicate SO question with the right answer - How can I scroll programmatically a div with its own scrollbars?

Voting to close mine.

Answer

Owen picture Owen · Aug 1, 2017

I've recently had a problem with a table header that had inputs as filters for each column. Tabbing through the filters would move the focus, but if one of the inputs wasn't visible or if it was partly visible, it would only JUST bring the input into view, and I was asked to bring the full input and column into view. And then I was asked to do the same if tabbing backwards to the left.

This link helped to get me started: http://www.webdeveloper.com/forum/showthread.php?197612-scrollIntoView-horizontal

The short answer is that you want to use:

document.getElementById('myElement').scrollLeft = 50;

or:

$('#myElement')[0].scrollLeft = 50;

Here's my solution (which may be overkill for this question, but maybe it'll help someone):

// I used $.on() because the table was re-created every time the data was refreshed
// #tableWrapper is the div that limits the size of the viewable table
// don't ask me why I had to move the head head AND the body, they were in 2 different tables & divs, I didn't make the page

$('#someParentDiv').on('focus', '#tableWrapper input', function () {
    var tableWidth = $('#tableWrapper')[0].offsetWidth;
    var cellOffset = $(this).parent()[0].offsetLeft;
    var cellWidth = $(this).parent()[0].offsetWidth;
    var cellTotalOffset = cellOffset + cellWidth;

        // if cell is cut off on the right
    if (cellTotalOffset > tableWidth) {
        var difference = cellTotalOffset - tableWidth;
        $('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft = difference;
        $('#tableWrapper').find('.dataTables_scrollBody')[0].scrollLeft = difference;
    }
        // if cell is cut off on the left
    else if ($('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft > cellOffset) { 
        $('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft = cellOffset;
        $('#tableWrapper').find('.dataTables_scrollBody')[0].scrollLeft = cellOffset;
    }
});