Saturday, 31 March 2018

css sticky header


title
title
content
content
content
content
content
content


<style>
.my-title{
    height:30vh;
    width:100%;
    background-color:darkorange;
}

.my-header{
    height:20vh;
    width:100%;
    background-color:aqua;
}

.my-content{
    height:200vh;
    width:100%;
    background-color:lawngreen;
}

.my-sticky{
    top:0;
    position:absolute;
}

.my-sticky+.my-content{
    padding-top:40vh;
}

.my-body{
    height:100vh;
    overflow-y:scroll; 
    text-align: center;
    font-size: 10vh;
}

.my-outer-body{
    position:relative;
}



</style>

<br />
<div class="my-outer-body" id="outer_body">
    <div class="my-body" id="my_body" onscroll="scroll_function()">
        <div class="my-title">
        title<br />
        title</div>
        <div class="my-header" id="sticky_header">
        header</div>
        <div class="my-content" id="my_content">
        content<br />
        content<br />
        content<br />
        content<br />
        content<br />
        content</div>
     </div>
</div>
<script type="text/javascript">
       
        var is_sticky = false;

        function scroll_function () {         

            var sticky_header = document.getElementById("sticky_header");
            var my_content = document.getElementById("my_content");

            var bodyRect = document.getElementById("outer_body").getBoundingClientRect();
            var headerRect = sticky_header.getBoundingClientRect();
            var contentRect = my_content.getBoundingClientRect();

            var header_Offset_body = headerRect.top - bodyRect.top;
            var content_Offset_header = contentRect.top - headerRect.bottom;


            if (!is_sticky && header_Offset_body <= 0) {
                sticky_header.classList.add("my-sticky")
                sticky_header.style.right = "3vh"; 
                sticky_header.setAttribute("style", "width:" + my_content.clientWidth + "px"); 
                is_sticky = true;
            }

            if (is_sticky && content_Offset_header > 0) {
                sticky_header.classList.remove("my-sticky");
                is_sticky = false;
            }

        }     

    </script>

reference:
https://www.w3schools.com/howto/howto_js_sticky_header.asp
https://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element
https://stackoverflow.com/questions/35070308/how-to-set-width-of-div-to-another-divs-width

No comments:

Post a Comment