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
                    } else { //try and and bring bottom of container to bottom of screen
                        $(window).scrollTop(elemTop -  ($(window).height() - $(container).height()));





Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.