Search code examples
jqueryhtmltextopacityparallax

How to initiate jquery count when passing div instead of top of page?


I'm trying to figure out how to get the following script to start counting the opacity when I pass the surrounding container #box instead of start counting the opacity at the very top of the page.

Anyone has a clue?

Script:

function parallaxFade() {
    scrollPos = $(this).scrollTop();
    $('#boxtext').css({
        'opacity': 1-(scrollPos/100)
    });
}

HTML:

<div class="box" id="box">
    <h3 class="boxtext" id="boxtext">Heading</h3>
</div>

Solution

  • We can compare the scroll position (ScrollPos here) to the #box position that we get using jQuery position(). The visual effect won't be remarked here so I kept it for Demo purpose. It's confusing so if you need it to change opacity strictly after the #box container, you change the condition to :

    if (scrollPos > pos+$('#box').height()) {
    

    function parallaxFade(pos) {
        var  opa = $('#boxtext').css('opacity');
        scrollPos = $(this).scrollTop();
        if (scrollPos > pos) {
        $('#boxtext').css({
            'opacity': 1-(scrollPos/(100+pos))
        });
        } else{
        
        $('#boxtext').css({
            'opacity': 1-(1/(100+scrollPos))
        });
        }
        //console.log(opa);
    }
    $(document).scroll(function() {
    var pos = $('#box').position().top;
    parallaxFade(pos);
    });
    .box{
    width:200px;
    height:200px;
    background-color:red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div class="ipsum">
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <div class="box" id="box">
        <h3 class="boxtext" id="boxtext">Heading</h3>
    </div>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    <p>Lorem Ipsum Lorem IpsumLorem Ipsum</p>
    
    </div>