Search code examples
javascriptjqueryjquery-uijquery-ui-autocomplete

Adding Scroll to Div Function With UI Auto Complete


Can you please take a look at This Demo and let me know how I can enable scroll to div of selected item from auto complete?

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
        $('html,body').animate({
               scrollTop: $("#"+ this.value).offset().top
         });
    }).change();
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

but I am getting this error

Uncaught TypeError: Cannot read property 'top' of undefined


Solution

  • The change event does not exist so your code is not being triggered. you have to do it this way:

    $(document).ready(function () {
        $('#tags').on('autocompleteselect', function (e, ui) {
            $('#tagsname').html('You selected: ' + ui.item.value);
            $('html,body').animate({
                   scrollTop: $("#"+ this.value).offset().top
             });
        });
    });
    

    Check this demo.