jQuery Scroll to Focused Element

Using jQuery automatically scroll to the selected element (in this case, on a form). Used for dodging overlap of position:fixed elements.

by Preston Badeer

HTML

<div id="stick"></div>
<form>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
    <br/>
    <input type="text" />
</form>

CSS

html, body {
    height: 900px;
}
#stick {
    background: rgba(0, 0, 0, 0.5);
    height: 200px;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
}

JavaScript

$('input').focus(function () {
    $('html, body').animate({
        scrollTop: $(this).offset().top + 'px'
    }, 'fast');

    /*
    $form = $(this).closest('form');
    $field = $(this);
    // Accounts for positioning inside of scrollable elements
    var scroll = $form.scrollTop() + ($field.position().top - $form.position().top) - ($form.height() / 2) + ($field.height() / 2);

    $('form').animate({
        scrollTop: scroll + 'px'
    }, 'fast');
    */
});