How to scroll a container or element into view using jQuery javascript in your html.

I had a simple need. This functionality expands on the way I was bringing a Kendo Grid detail template into view on selection. I wanted a better look feel so I dug a little deeper.

I adapted this function to work on any container or element. I am using this in a custom table that when click make another row visible. I wanted the whole row to be displayed if possible, but only scroll if I needed to. This code will scroll only if needed, load the container to appear at least at the bottom and if the container is too large, drags it to the top.

Super easy to use and great look and feel.

     function scrollContainerIntoViewIfNeeded(container) {

                var docViewTop = $(window).scrollTop();
                var docViewBottom = docViewTop + $(window).height();

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

                var isScrolled = ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));

                if (!isScrolled) {
                    if ($(container).height() > $(window).height()) { //then just bring to top of the container
                        $(window).scrollTop(elemTop)
                    } else { //try and and bring bottom of container to bottom of screen
                        $(window).scrollTop(elemTop -  ($(window).height() - $(container).height()));
                    }

                }
        }

 

usage.

scrollContainerIntoViewIfNeeded($("#myContainer"));

Happy coding.

How to scroll the detail row of a Kendo Grid into view on select

I decided I liked the idea of only having one detail pane at a time in my web grid. It gets too cluttered having a number of them open. I got feedback from my users that when selecting a row towards the end of the screen, they had to then scroll to see all the details.

I did a simply time cost analysis and instead of changing the UI to show the data in a popup, it was faster and cheaper just to scroll down the page. Simple, eh.

Here is the script to do a scroll when a row is selected in the Kendo Grid to ensure the detail pane is visible.

  function engagementRowSelected(e) {

            var eventTarget = (event.target) ? $(event.target) : $(event.srcElement);

            var grid = $("#engagementsContainer").data("kendoGrid");
            var gridSource = grid.dataSource;
            var selectedRow = this.select()[0];

            var position = $(selectedRow).position();
            $(window).scrollTop(position.top);

        }

I left out all the code that does the selection, and forcing to display only one row at a time. If that is something people want to see or use, I can post that as a simple demo later.

Happy coding!