Search code examples
jqueryhtmlcssscrolltop

stopping a fixed position when it reaches to almost the bottom


I have read quite a few threads on stackoverflow about this situation and tried their ways either with jquery or html /css but mine just keeps on not working the way wanted. Can someone please give me a hand?

My html

<div id="product-summary-position">
    <div id="product-fixed">
        <div id="product-summary">
            <header>Product Summary</header>
            <div class="price" name="product-summary-price">$0.00</div>
            <header>Have Questions?</header>
            <p>Call our Product Experts<br> 1-877-270-3311</p>
            <button class="btn-reset">Reset</button>
        </div>
    </div>
</div>

my css

#product-summary-position{float: right;
    height: 185px;
    width: 185px;}

div#product-summary {
    font-family: 'roboto';
    height: 230px;
    width: 185px;
    background-color: #2A0092;
    border-radius: 5px;
    text-align: center;
    color: #FFF;
    top: 250px;
}

div#product-fixed {
    position: fixed;
}

I have a footer that's approximate 400px each time I scroll down the product summary would overlap the footer. I tried using what I can find online but couldn't figure out how to make it work properly.

Thanks in advance.

Edit : jsfiddle


Solution

  • Try this.


    Solution

    Change yours HTML to this:

    <div id="product-summary-position">
        <div id="product-fixed">
            <div id="product-summary">
                <header>Product Summary</header>
                <div class="price" name="product-summary-price">$0.00</div>
                <header>Have Questions?</header>
                <p>Call our Product Experts
                    <br>1-877-270-3311</p>
                <button class="btn-reset">Reset</button>
            </div>
        </div>
    </div>
    
    <footer id="wholeFooter">
        <!-- move entire footer to separate block element -->
        <div class="footer2">
            ...
        </div>
        <div class="footer2">
            ...
        </div>
    </footer>
    

    And, javascript:

    var doc = $(document); 
    
    doc.scroll(function () {
         // make sure to wrap yours entire footer in some css selector
        var footer = $('#wholeFooter');
        var p = $('#product-fixed');
        var s = $('#product-summary-position');
    
        var top = doc.scrollTop() + s.offset().top * 2 + p.height();
        var footerTop = footer.offset().top;
    
        var offset = footerTop - top;
    
        if (offset < 0) {
            p.css({'margin-top': '' + offset + 'px'});
        } else {
            p.css({'margin-top': 0});
        }
    
    });
    

    Upd.*

    Separate "fixed" class was unnecessary.