Scroll if element is not visible

macpak picture macpak · Jun 2, 2011 · Viewed 47.7k times · Source

how to determine, using jquery, if the element is visible on the current page view. I'd like to add a comment functionality, which works like in facebook, where you only scroll to element if it's not currently visible. By visible, I mean that it is not in the current page view, but you can scroll to the element.

Answer

Loktar picture Loktar · Jun 2, 2011

Live Demo

Basically you just check the position of the element to see if its within the windows viewport.

function checkIfInView(element){
    var offset = element.offset().top - $(window).scrollTop();

    if(offset > window.innerHeight){
        // Not in view so scroll to it
        $('html,body').animate({scrollTop: offset}, 1000);
        return false;
    }
   return true;
}