Search code examples
javascripthtmlfixed

Hide fixed element when past another


Here is a small demo:

HTML

<body>
    <div class="container-empty"></div>
    <ul>
        <div id="divfix"><li id="lifix">Text 1 FIXED</li></div>
        <div id="divfix2"><li id="lifix2">Text 2 FIXED</li></div>
        <div id="divfix3"><li id="lifix3">Text 3 FIXED</li></div>
    </ul>
    <div class="container-footer"></div>
</body>

JSCRIPT

var toppag=$("#lifix,#lifix2,#lifix3");
var pag=$("#divfix,#divfix2,#divfix3");

toppag.css({position:"relative"});


$(window).scroll(function () {
    var scroll=$(this).scrollTop();
    pag.each(function(i,n){
        if(scroll < $(this).offset().top) {
            toppag.eq(i).css({'position':'relative'});
        }
        if(scroll > ($(this).offset().top + toppag.eq(i).height()))  {
            toppag.eq(i).css({'position':'fixed',"top":"0"});
        }
    }); 
});

DEMO HERE: https://jsfiddle.net/Kigris/4cb0ygun/2/

I want to hide "Text 1 FIXED" when reaches "Text 2 FIXED" and so on. Also, when all reach the footer hide them all.


Solution

  • Try adding

     var footer = $(".container-footer");
     pag.css('position', 'relative'); under toppage.css etc
    

    and

     if(scroll > footer.offset().top){
        toppag.hide();
     }else{ toppag.show();}
    

    and

    toppag.eq(i-1).parent().css({'z-index':"0"});
    

    in your second if(scroll)

    What this does is makes sure the fixed element gets pushed to the bottom in stacking order.

    DEMO: Demo