annatriant
12/16/2014 - 2:40 PM

Fixed box to top of window on scroll

Fixed box to top of window on scroll

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Fixed box to header</title>
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .fixed {
            position: fixed;
            top: 0;
            z-index: 99999;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-md-12">
                <div class="well" style="height: 200px;">
                    (200px high)
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div id="box">
                    <div class="well">
                        FIXED BOX
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="well" style="height: 1000px;">
                    (1000px high)
                </div>
            </div>
        </div>

    </div>


</body>

</html>

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        var top = $('#box').offset().top;
        $(window).scroll(function (event) {
            var y = $(this).scrollTop();
            if (y >= top)
                $('#box').addClass('fixed');
            else
                $('#box').removeClass('fixed');
        });
        $('#box').width($('#box').parent().width());

    });
</script>