Joe Borg
Joe Borg

Reputation: 63

Header Div position fixed on top of page but on load show a div on top of it

I've been trying to figure out the correct way to do this. Three divs, Advert Div on top, Header Div beneath, and Content Div furthest down. On pg load I intend to have the advert div show, but upon scrolling I intend to keep the header div on position fixed, top:0px i.e. at the top of the page over the content.

Am aware of using position fixed in CSS, yet they way I need it contradicts this attribute since I need the header div to move further up till page top on scroll and stay position fixed there.

Am also aware of the possibility in having all three divs on top of each other, and upon scroll, using jquery I'll hide the advert div and naturally the header div would move up to the top and maintain its position fixed attribute.

any suggestions? JS Fiddle link here for a quick example

Upvotes: 1

Views: 2632

Answers (2)

Benjamin
Benjamin

Reputation: 2670

Here is the code

$(document).ready(function () {
    var top_fixed;
    if ($('#header-con').length > 0)
    {
        top_fixed = $('#header-con').offset().top;
    }
    $(window).scroll(function () {
        if ($('#header-con').length > 0)
        {
            $('#header-con').toggleClass('fixed', $(window).scrollTop() > top_fixed);
        }
    });
});

DEMO

More Clear CSS

*{
    margin:0;
    padding:0;
}

#advert-con { color:yellow;height:130px;background:blue;width:100%;margin:0px;padding:0px;display:block; }
#header-con { height:170px;background:black;color:#fff!important;margin:0px;padding:0px; }
#content-con { height:700px;background:purple; }

.fixed {
    position: fixed;
    top: 0;
    width:100%;
}

UPDATED DEMO

Making the #advert-con fixed

.container{
    margin-top:130px;
    display:inline-block;
    width:100%;
}
.container:after{
    display:block;
    clear:both;
    content:"";
}

FINAL DEMO

Upvotes: 0

Tony
Tony

Reputation: 364

You can do something like this (using your example):

HTML:

<div id="advert-con">
<h3>
    <br />
    <br />
    ADVERT DIV MUST BE OVERLAYED WITH BLACK DIV UPON SCROLLING </h3>
</div>
<!--end advert-con-->
<div id="header-con">
    <h2>
        <br />
        <br />
        HEADER DIV MUST REMAIN VISIBLE ON TOP</h2>
</div>
<!--end header-con-->
<div id="content-con">
    <h4>Content Words Text Context</h4>
</div>
<!--end content-con-->

Jquery:

$(document).ready(function () {
   var header = $('#header-con');
   var distanceFromTop;
   if (header.length > 0)
   {
       distanceFromTop = header.offset().top;
   }
   $(window).scroll(function () {
       if (header.length > 0)
       {
           header.toggleClass('sticky-top', $(window).scrollTop() > distanceFromTop);
       }
   });
});

CSS:

.sticky-top {
    position: fixed;
    top: 0;
    width:100%;
}

Hope that helps :)

Upvotes: 1

Related Questions