user3847141
user3847141

Reputation: 253

Scroll then fix to top header in html

So, i'd like to have an header working similarly to the one here http://www.blackmesasource.com/ , the only problem being I know nothing about javascript and jquery, can anyone help me?

Upvotes: 0

Views: 1530

Answers (2)

Tony Merryfield
Tony Merryfield

Reputation: 403

Nice - I just knocked this up for you - it's rough and has had no cross-browser testing:

<style type="text/css">

    body {
        padding:0;
        margin:0;
    }

    #hero {
        background-color:#eee;
    }

    nav {
        position:absolute;
        bottom:0;
        left:0;
        background-color:#ccc;
        box-sizing:border-box;
        width:100%;
        padding:20px;
    }

    nav.fixed-position {
        position:fixed;
        top:0;
        bottom:initial;
    }

</style>

<body>

    <div>

        <div id="hero">

            <nav id="nav-menu">
                Your nav here
            </nav>

        </div>

        <section style="height:2000px;">

            content

        </section>

    </div>

    <script type="text/javascript">

        var hero = document.getElementById('hero'),
            nav = document.getElementById("nav-menu"),
            viewportHeight = Math.max(window.innerHeight || 0),
            navOffsetTop = nav.offsetTop;

        hero.style.height = viewportHeight + 'px';

        var hasScrolled = function() {

            var fromTop = document.body.scrollTop || document.documentElement.scrollTop || 0;

            if (navOffsetTop < fromTop) {
                nav.classList.add('fixed-position');
            } else {
                nav.classList.remove('fixed-position');
            }

        }

        window.addEventListener('scroll', hasScrolled);

    </script>

</body>

You can drop this into an empty file and run it in your browser to see the result - I tested it in Firefox with no problems but as I say, it will need additional work; such as:

  • Crossbrowser - depending on what level of IE support you plan to have, classList might not work.
  • Optimisation - currently the hasScrolled function fires every time the user scrolls, you might want to find a way to limit that.
  • Global vars - I've made no attempt to use a nice clean namespace for the JS, something else you might like to look into.

Additionally, this doesn't require jQuery, but given what I've just suggested you need to do you might want to look into using it - it's mainly crossbrowser which will help you out alot if you don't really know JS.

Upvotes: 3

Ram kumar
Ram kumar

Reputation: 3162

You can see best resources here. Just follow same structure https://css-tricks.com/scroll-fix-content/

Upvotes: 0

Related Questions