Ellis Johnston Ellis Johnston - 2 months ago 5
CSS Question

JavaScript - trying to change colour of span elements when scrolling down

I have a side bar nav that shows by clicking the button which is made up of span elements - it is currently white.

Here is the HTML:

<div id="sidebar-btn">
<span></span>
<span></span>
<span></span>
</div>
</div>


CSS for the span:

div#sidebar-btn span{
height: 1px;
background:white;
margin-bottom: 5px;
display: block;
}


Here is another class I have created in order for it turn black once the page has been scrolled down a certain amount, with the .toggleClass function. This is because there is a section of content once the user has scrolled and it has a white background - therefore the button won't show up because it's white too.

div#sidebar-btn.black span{
height: 1px;
background:black;
margin-bottom: 5px;
display: block;
}


Here is the Javascript that is attempting to toggle the class for the sidebar button for the class to change to 'black'.

<script>
$(document).ready(function(){
$(window).scroll(function() { // check if scroll event happened
if ($(document).scrollTop() > 50) { // check if user scrolled more than 50 from top of the browser window

$("#sidebar-btn")(function(){
$("#sidebar-btn").toggleClass('black');
});
}
});
});
</script>


It's not working. I'm good at HTML and CSS but not great at JavaScript, and there's clearly an error here. Not sure how to go about fixing it.

Answer

Your problem is the on scroll listener called every time scrollTop changed, so when the scrollTop more than 50, you start toggling the black class. Thats mean you toggled the black every single callback of the scroll listener. What you should do, is to check if the scrollTop more than 50 and then check also if your does not have the class black and add it, and if the scrollTop bellow 50 you have to check if your element have the class black and remove it.

Full Example

$(document).ready(function(){
  $(window).scroll(function() {
    if ($(document).scrollTop() > 50)  {
      if(!$("#sidebar-btn").hasClass('black')){
        $("#sidebar-btn").addClass('black');
      }
    }else{
      if($("#sidebar-btn").hasClass('black')){
        $("#sidebar-btn").removeClass('black');
      }
    }
  });
});
div#sidebar-btn span{
  background: whitesmoke;
  margin-bottom: 5px;
  height: 100px;
  width: 100%;
  display: block;
}

div#sidebar-btn.black span{
  background:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="sidebar-btn">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
</div>

Comments