Running one code with variables for 2 divs

Trying to run the same function for 2 separate divs. It should apply the class 'header-hide'/'header-show' when the user scrolls a certain distance (offset).

The working code for one div/element (no variables) is

jQuery(document).ready(function($){


// adjust this number to select when your button appears on scroll-down
var offset = 75,

// bind with the button link
$animation = $('header');

// apply animation
$(window).scroll(function(){
    ( $(this).scrollTop() > offset ) ? $animation.addClass('header-hide').removeClass("header-show"):
    $animation.addClass('header-show').removeClass("header-hide");
});

});

But when I try to apply it to 2 divs using variables, doesn't work

$(document).ready(function($) {

      function reusuableAnimationFunc(elementName, offset, hideClass, showClass) {
        $animation = $(elementName);

        $(window).scroll(function() {
          ($(this).scrollTop() > offset) ? $animation.addClass(hideClass).removeClass(showClass):
            $animation.addClass(showClass).removeClass(hideClass);
        });
      });

    reusuableAnimationFunc('header', 70, 'header-hide', 'header-show') 
    reusuableAnimationFunc('#top-btn', 300, 'element-hide', 'element-show')
.element-hide,
.header-hide {
  opacity: 0;
  visibility: hidden;
}

.element-show,
.header-show {
  opacity: 1;
  visibility: visible;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<header class="jumbotron header-show">

  <div id="jumbo-wrap">
    <h3>Title</h3>
    <h1>Sub-title</h1>
  </div>

</header>

<div id="top-btn" class="element-show">
  <a href="#"> ... </a>
</div>

Answers 1

  • You have a syntax error in javascript function. You are closing reusuableAnimationFunc function with });, it should be }. Also, you need to close document.ready() function at the end. That function is never closed.

    $(document).ready(function($) {    
              function reusuableAnimationFunc(elementName, offset, hideClass, showClass) {
                $(window).scroll(function() {
                $animation = $(elementName);                
                  ($(this).scrollTop() > offset) ? $animation.removeClass(showClass).addClass(hideClass):
                    $animation.addClass(showClass).removeClass(hideClass);
                });
              }    
            reusuableAnimationFunc('header', 70, 'header-hide', 'header-show');
            reusuableAnimationFunc('#top-btn', 300, 'element-hide', 'element-show');
            });
    

    P.S move $animation = $(elementName); inside windows.scroll function


Related Articles