Vachos
Vachos

Reputation: 377

Add/remove class with jquery based on vertical scroll

i need to add class after 1070 i have the code for that and its work great:

jQuery( document ).ready(function( $ ) {
	$(window).scroll(function() {
	    var scroll = $(window).scrollTop();
      
	    if (scroll >= 1070) {
		$(".header-main").addClass("extrablack");
	    } else {
		$(".header-main").removeClass("extrablack");
	    }
	});
});

now i need to add class extrablack in 1070 but remove in 1580 how can i do that? I need the class stay between 1070 and 1580 of website. thanks

Upvotes: 0

Views: 3335

Answers (2)

Scaramouche
Scaramouche

Reputation: 3257

Is this what you were looking for?

jQuery( document ).ready(function( $ ) {
	$(window).scroll(function() {
	    var scroll = $(window).scrollTop();
      
	    if (scroll >= 1070 && scroll < 1580) {
		$(".header-main").addClass("extrablack").text(scroll);
	    } else {
		$(".header-main").removeClass("extrablack").text(scroll);
	    }
	});
});
.header-main{
  position: fixed;
  width: 100%;
  height: 100px;
  background: lightgray;
  color: white;
  text-align: center
}

.header-main.extrablack{
  background: black
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header-main"></div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

Upvotes: 2

Elroy Jetson
Elroy Jetson

Reputation: 968

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

        if (scroll >= 1070 && scroll <= 1580) {
          $(".header-main").removeClass("extrablack");
          return;
        }

        if (scroll >= 1070) {
          $(".header-main").addClass("extrablack");
        }   
    });
});

Upvotes: 0

Related Questions