1

I have a table where you can select an element and then when ever you press the up or down arrow key the next or previous table row will be selected.

for this purpose i have created the following jquery:

    $(document).keydown(function(e) {
    var ar=new Array(33,34,35,36,37,39);
    if(selected_row_id != null){
        var key = e.which;
        // up
        if(key == 38){
            $('#'+selected_row_id).prev().trigger('click');
            e.preventDefault();
        }
        //down
        if(key == 40 ){
            $('#'+selected_row_id).next().trigger('click');
            e.preventDefault();
        }

        if($.inArray(key,ar) > -1) {
            e.preventDefault();
            return false;
        }
        return true;
    }
});

This works fine however it has one mistake that annoys me. When a table row is further down than you can actually see on the screen (meaning that you would have to scroll) the window doesnt scroll automaticly.

My question is how is it possible to make sure that the window scrolls when an element is not visible on the screen?

display-name-is-missing
  • 4,742
  • 4
  • 24
  • 39
Marc Rasmussen
  • 17,383
  • 66
  • 172
  • 305

2 Answers2

1

Here is a function taken from here:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
}

Returns true if the element is completely visible in the window, false otherwise.

If false is returned, then you can scroll your window appropriately.

Community
  • 1
  • 1
FastTrack
  • 8,191
  • 14
  • 52
  • 75
0

Yes, this is possible.

Look at ScrollTo: http://www.w3schools.com/jsref/met_win_scrollto.asp

CodeViking
  • 226
  • 1
  • 6