Fixed header on scroll using jquery in ASP.NET MVC

Now days a very common thing on many website is fixed header on top of screen while scrolling. Facebook has a similar header which remains on top of content. Here we will see how to add such header in ASP.NET MVC master page.

Master Page

Add Latest jQuery file.
Create a \div with ID header apply style as per your requirement,

    <div id="header" style="width: 100%; padding: 0px; height: 100px; background-color: #3275A8; text-align: center;">
        <h2>Header</h2>
    </div>

Now on document read add the script as below

    <script type="text/javascript">
        $(document).ready(function () {
            var div = $('#header');
            var start = $(div).offset().top;

            $.event.add(window, "scroll", function () {
                var p = $(window).scrollTop();
                $(div).css('position', ((p) > start) ? 'fixed' : 'static');
                $(div).css('top', ((p) > start) ? '0px' : '');
            });

        });
    </script>

That it. on the inner pages just add content.

Complete code

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>@ViewBag.Title</title>
    <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var div = $('#header');
            var start = $(div).offset().top;

            $.event.add(window, "scroll", function () {
                var p = $(window).scrollTop();
                $(div).css('position', ((p) > start) ? 'fixed' : 'static');
                $(div).css('top', ((p) > start) ? '0px' : '');
            });

        });
    </script>
</head>
<body style="margin: 0 auto;">
    <div id="header" style="width: 100%; padding: 0px; height: 100px; background-color: #3275A8; text-align: center;">
        <h2>Header</h2>
    </div>
    <div>
        @RenderBody()
    </div>
</body>
</html>
Advertisements
This entry was posted in css, jQuery, MVC and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s