Search code examples
jqueryasp.net-mvcasp.net-mvc-4kendo-uikendo-grid

Kendo Grid scroll to selected row


I want to be able to call a function that scrolls the Kendo grid to the selected row. I´ve already tried some methods but none of them worked,

for instance I tried this:

var grid = $("#Grid").data("kendoGrid"),
    content = $(".k-grid-content");
content.scrollTop(grid.select());

I´ve also tried this:

var gr = $("#Grid").data("kendoGrid");
var dataItem = gr.dataSource.view()[gr.select().closest("tr").index()];
var material = dataItem.id;
var row = grid.tbody.find(">tr:not(.k-grouping-row)").filter(function (i) {
    return (this.dataset.id == material);
});
content.scrollTop(row);

Can anyone point me in the right direction please? :)

--- EDITED ---

For other reasons I can not bind to the change event so I have to be able to call a function the scrolls the list to the selected row. This is what I tried with the answer @Antonis provided for me.

var grid = $("#Grid").data("kendoGrid")
grid.element.find(".k-grid-content").animate({  
    scrollTop: this.select().offset().top  
 }, 400);

When I tried this it scrolled somewhat down the list but not to the selected row. Am I use the grid object in a wrong way by calling scrollTop on it?

This too:

var grid = $("#ItemGrid").data("kendoGrid");
grid.scrollToSelectedRow = function () {
    var selectedRow = this.select();
    if (!selectedRow) {    
        return false;    
    }
    this.element.find(".k-grid-content").animate({
        scrollTop: selectedRow.offset().top  
    }, 400);
    return true;
    };

grid.scrollToSelectedRow();

Solution

  • You can do it automatically when a row is selected. Bind a function to the 'change' event, and in there, you can scroll to the selected row. ( assuming you can select only one row, which is given by the 'this.select()' )

    JSFiddle example

    the 'change' handler

    //    bind to 'change' event
    function onChangeSelection(e) {
    
        //    animate our scroll
        this.element.find(".k-grid-content").animate({  // use $('html, body') if you want to scroll the body and not the k-grid-content div
            scrollTop: this.select().offset().top  //  scroll to the selected row given by 'this.select()'
         }, 400);
    }