Position fixed on a div after scrolling for a predefined amount of px

I'm working on a "stupid" effect on my webpage that has a simple parallax effect.

I want #menu to assume "position: fixed;" instead of "position: relative;" after scrolling for the height of the header (so after 100px).

This is my code, at the moment:

<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">

body {
    margin: 0;
}

header {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: -1;
    height: 100px;
    background: green;
}

.wrapper {
    margin-top: 100px;
    margin-bottom: 60px;
}

.content {
    position: relative;
    z-index: 1;
    border-top: 1px solid black;
    border-bottom: 1px solid black; 
    background: white;
    min-height: 1500px;
}

#menu{
    width: 100%;
    height: 50px;
    background-color: red;
    position: relative;
}

footer {
    width: 100%;
    position: fixed;
    z-index: -1;
    bottom: 0;
    background: black;
    color: white;
    height: 60px;
}

</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
    $(window).scroll(function(){
        if ($(window).scrollTop() >= $(header).height()) {
             $("#menu").css('position', 'fixed');
             alert("I'm working fine.");
        }
    });
</script>
</head>

<body>
    <div class="wrapper">
        <header id="head">
            <h1>HEADER</h1>
        </header>

        <div class="content">
            <div id="menu">I SHOULD BE FIXED AFTER SCROLLING FOR 100px.</div>
            <h1>CONTENT</h1>
        </div>

        <footer>
            <h1>FOOTER</h1>
        </footer>
    </div>
</body>

</html>

JSFiddle

It's like the JQuery script is not working and I don't know why

Any help would be really appreciated, thanks in advance.

Answers 1

  • I ran it on my website. The console caught the error. header is not defined. Change code in to this:

    <script type="text/javascript">
        $(window).scroll(function(){
            if ($(window).scrollTop() >= $('#head').height()) {
                 $("#menu").css('position', 'fixed');
                 alert("I'm working fine.");
            }
        });
    </script>
    

Related Articles