finners
finners

Reputation: 885

Adding a class between when user scrolls between 200px and 300px only

I'm trying to add a class to div when a user scrolls down the page. When they scroll 200px down the page I want a class to be added and then once the user scrolls down 300px I want the class to be removed. Similarly, when the user scrolls back up the page and is 300px from the top, I then want the class to be added until it gets to 200px and then removes the class.

I've tried so many variations but I think I'm approaching it all wrong. Here's a jsfiddle of how far I've gotten so far - http://jsfiddle.net/v8my3sr1/

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  if (scroll >= 200) {
    $(".trigger").addClass("wow");
  } else {
    $(".trigger").removeClass("wow");
  }
});

Upvotes: 0

Views: 145

Answers (2)

Mohammad
Mohammad

Reputation: 21489

You condition is incorrect. You should check that scroll value is between 200 and 300

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  if (300 >= scroll && scroll >= 200) {
    $(".trigger").addClass("wow");
  } else {
    $(".trigger").removeClass("wow");
  }
});

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  if (300 >= scroll && scroll >= 200) {
    $(".trigger").addClass("wow");
  } else {
    $(".trigger").removeClass("wow");
  }
});
.container {
  height: 2000px;
}
.trigger {
  margin-top: 300px;
  height: 400px;
}
.wow {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="trigger">
    <h1>Trigger container</h1>
  </div>
</div>

Also you can use .toggleClass() to simplifying code

$(window).on('scroll',function() { 
  var scroll = $(window).scrollTop();
  $(".trigger").toggleClass("wow", 300 >= scroll && scroll >= 200);
});

Upvotes: 4

Bojan Kolano
Bojan Kolano

Reputation: 283

Try something like this :

$(window).scroll(function(){

  var cutoff = $(window).scrollTop();

   $(".trigger").each(function(){
    if($(this).offset().top + $(this).height() > cutoff){
      panel.removeClass('wow');
      $(this).addClass('wow');
      return false;
    }
  })
})

Upvotes: 0

Related Questions