Size dependent on scroll

I want to know how to make a element opacity dependent on the scroll position of the page. For example, if my element is in the middle of the page, that element becomes more and more opaque, as the user scrolls to the middle.

Thank you!

here is solutions:

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Solution 1

You can use the following code, where ref1 and ref2 are the top and bottom position in window coordinates where the element became fully opaque, and fadeSize is the scroll amount needed to make the element fully invisible. The code automatically handles all elements with the class "ScrollFade":

$(function() {
    document.addEventListener('scroll', function(e) {
        var ref1 = $(window).height() * 0.4;
        var ref2 = $(window).height() * 0.6;
        var fadeSize = 100;
        $('.ScrollFade').each(function() {
            var $elem = $(this);
            var h = $elem.height();
            var top = $elem.offset().top - window.scrollY;
            var bottom = top + h;
            var opacity;
            if (top < ref1 && bottom > ref2 || ref1 < top && top < ref2 || ref1 < bottom && bottom < ref2) {
                opacity = 1;
            } else if (top > ref2) {
                opacity = 1 - (top - ref2) / fadeSize;
            } else if (bottom < ref1) {
                opacity = 1 - (ref1 - bottom) / fadeSize;
            opacity = Math.min(Math.max(0, opacity), 1);
            $elem.css('opacity', opacity);
body {
    height: 50cm;
    position: relative;

#myElem {
    position: absolute;
    top: 20cm;
    height: 3cm;
    width: 5cm;
    background-color: red;
    color: white;
<script src=""></script>
<div id="myElem" class="ScrollFade">Lorem ipsum</div>

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply