Search code examples
javascriptjqueryscrollhighlighting

JavaScript: Highlight a row when I scroll up/down


On my web page, I a table inside a DIV that is scrollable.

When I scroll down, I want to highlight the center most viewable row in my table.

How would I do that?

I found the following script that is close to what I desire --> www.rgagnon.com/jsdetails/js-0093.html

But this works only on the MouseOver event. I want this to work on not just the MouseOver event but also when I simply scroll up/down.


Solution

  • Use the scroll event.

    For example: (EDIT: Finally tested)

    var scrollElem = $('div#panel-hlisting-all');
    scrollElem.scroll(function() {
        var scrollElemPos = scrollElem.offset();
    
        var newCenter = $(document.elementFromPoint(
            scrollElemPos.left + scrollElem.width()  / 2,
            scrollElemPos.top  + scrollElem.height() / 2)
        ).closest('.hlisting');
    
        if(newCenter.is(".CenterRow")) return;
        $('.CenterRow').removeClass("CenterRow");
        newCenter.addClass('CenterRow');
    });
    

    EDIT: I changed the code to work with a specific element's scrollbar.
    3rd EDIT: I updated the code to prevent flicker.