Cam C. Cam C. - 10 days ago 7
Javascript Question

if window scroll amount -> then reverse back in jQuery

jQuery:

$(window).scroll(function() {
var scroll = $(window).scrollTop();

if (scroll >= 50) {
$(".class").addClass("bgposi");
// $(".top").addClass("fixd");
// $(".logo").addClass("maxwidth");
if (scroll >= 50) {
$(".class").addClass("bgposi");
// $(".top").addClass("fixd");
// $(".logo").addClass("maxwidth");
}
}

});


So, basically my class that I'm adding on scroll.
.bgposi
is moving the background image position when I scroll past
50px
on the page using
(window).scroll(function()
. Which works fine, so my first if statement alone.. However, I'm trying to reverse it with another if statement, when the user scrolls back up - this is where I'm failing.. any pointers?

Answer

Correct the following in your second if statement:

  • Do not nest it.
  • Change the comparison operator >= to <=.
  • Use removeClass.

Change:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 50) {
        $(".class").addClass("bgposi");
        // $(".top").addClass("fixd");
        // $(".logo").addClass("maxwidth");
       if (scroll >= 50) {
        $(".class").addClass("bgposi");
        // $(".top").addClass("fixd");
        // $(".logo").addClass("maxwidth");
        }
    }

});

To:

$(window).scroll(function() {
  var scroll = $(window).scrollTop();
  if (scroll >= 50) {
    $(".class").addClass("bgposi");
    // $(".top").addClass("fixd");
    // $(".logo").addClass("maxwidth");
  } else if (scroll <= 50) {
    $(".class").removeClass("bgposi");
    // $(".top").removeClass("fixd");
    // $(".logo").removeClass("maxwidth");
  }
});

You could cache some reused selectors (doing the lookup once), like so:

$(window).scroll(function() {
  var scroll = $(this).scrollTop();
  var $class = $(".class"),
    $top = $(".top"),
    $logo = $(".logo");

  if (scroll >= 50) {
    $class.addClass("bgposi");
    $top.addClass("fixd");
    $logo.addClass("maxwidth");
  } else if (scroll <= 50) {
    $class.removeClass("bgposi");
    $top.removeClass("fixd");
    $logo.removeClass("maxwidth");
  }
});

$(window).scroll(function() {
  var scroll = $(this).scrollTop();
  var $class = $(".class");

  if (scroll >= 50) {
    $class.addClass("bgposi");
  } else if (scroll <= 50) {
    $class.removeClass("bgposi");
  }
});
body {
  height: 200vh;
  background-color: peachpuff;
}
.class {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 20%;
  background-color: dodgerblue;
}
.class.bgposi {
  background-color: purple;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="class"></div>