1

I have a list like this: http://jsfiddle.net/Vtn5Y/559/

var li = $('li');
var liSelected;
$(window).keydown(function(e){
    if(e.which === 40){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.eq(0).addClass('selected');
            }
        }else{
            liSelected = li.eq(0).addClass('selected');
        }
    }else if(e.which === 38){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.last().addClass('selected');
            }
        }else{
            liSelected = li.last().addClass('selected');
        }
    }
});

Now I wonder how I can make the div scroll down to be able to see the selected item.

Thank you!

Onovar
  • 719
  • 1
  • 7
  • 19

2 Answers2

2

There is a similar question here: How to scroll to specific item using jQuery?

Solution is to use the scrollTop property like so:

var container = $('div'),
scrollTo = $('#row_8');

container.scrollTop(
    scrollTo.offset().top - container.offset().top + container.scrollTop()
);

// Or you can animate the scrolling:
container.animate({
    scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});​

Working example: http://jsfiddle.net/xY7tx/406/

Community
  • 1
  • 1
1

sorry, my first answer had a problem.

try this:

var li = $('li');
var liSelected;
$(window).keydown(function(e){
    if(e.which === 40){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.eq(0).addClass('selected');
            }
        }else{
            liSelected = li.eq(0).addClass('selected');
        }
    }else if(e.which === 38){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.last().addClass('selected');
            }
        }else{
            liSelected = li.last().addClass('selected');
        }
    }
    $('div').scrollTop(liSelected.position().top - $('div').position().top + $('div').scrollTop());
});

JSFidle here

FabioG
  • 2,858
  • 3
  • 31
  • 45