Scroll to element only if not in view – jQuery

All modern Browsers support this. Visit: http://caniuse.com/#search=scrollIntoView

function scrollIntoViewIfVisible(target) { 
    if (target.getBoundingClientRect().bottom > window.innerHeight) {
        target.scrollIntoView(false);
    }
    
    if (target.getBoundingClientRect().top < 0) {
        target.scrollIntoView();
    } 
}

Update

The target has to be an Element. If you use jQuery call the function like this:

scrollIntoViewIfVisible($(".target")[0]);

Leave a Comment