Onovar
Onovar

Reputation: 739

Autocomplete scroll

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!

Upvotes: 1

Views: 431

Answers (2)

FabioG
FabioG

Reputation: 2986

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

Upvotes: 1

Daniel Knecht
Daniel Knecht

Reputation: 41

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/

Upvotes: 2

Related Questions