Div appears on page load

I have the following code which applies class which shows/hide a div.

$(document).ready(function($) { 
      function reusuableUpAnimFunc(elementName, offset, hideClass, showClass) {
        $(window).scroll(function() {
        $animation = $(elementName);                
          ($(this).scrollTop() > offset) ? $animation.removeClass(hideClass).addClass(showClass):
            $animation.addClass(hideClass).removeClass(showClass);
        });
      } 

reusuableUpAnimFunc('#top-btn', 400, 'element-hide', 'element-show');
});

css

.element-hide {
 opacity: 0;
 visibility: hidden;
}

.element-show {
 opacity: 1;
 visibility: visible;
}

Problem is when the page first loads the div is visible, then as soon as user scrolls it disappears, then reappears as it's supposed to. I want it to be opacity 0 until the offset distance is reached

Answers 1

  • You could trigger the scroll callback function on page load with triggerHandler('scroll'). I would write it as follows:

    $(document).ready(function($) {
        function swapClass(selector, class1, class2, setClass2) {
            $(selector).toggleClass(class1, !setClass2).toggleClass(class2, setClass2);
        }
    
        function reusuableUpAnimFunc(selector, offset, hideClass, showClass) {
            $(window).scroll(function () {
                swapClass(selector, hideClass, showClass, $(this).scrollTop() > offset);
            }).triggerHandler('scroll');
        }
    
        reusuableUpAnimFunc('#top-btn', 50, 'element-hide', 'element-show');
    });
    .element-hide {
        opacity: 0;
        visibility: hidden;
    }
    
    .element-show {
        opacity: 1;
        visibility: visible;
    }
    p { height: 50px };
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p>scroll down...<p>
    <div id="top-btn">This will appear on scrolling</div>
    <p></p><p></p><p></p><p></p><p></p>

    Or, you could just call the function explicitly:

        // ...
        $(window).scroll(function () {
            swapClass(selector, hideClass, showClass, $(this).scrollTop() > offset);
        });
        // Call it now:
        swapClass(selector, hideClass, showClass, $(this).scrollTop() > offset);
        // ...
    

Related Articles