Can i use a percentage as a value in scrolltop?

I'm pretty new to HTML in general. I have the following code and I was wondering if there is any way of using a percentage instead of a fixed value. I have searched but I couldn't find a simple solution.

$(window).scroll(function () { 
    if ($(this).scrollTop() > 445 && $(this).scrollTop() < 1425 ) { 
        nav.addClass("f-nav");
    } else { 
        nav.removeClass("f-nav");
    } 

Basically what I want is the class to be removed after scrolling past 80% of the page, instead of after 1425px so that it also works properly if the window size is modified.

Upvotes: 5

Views: 2468

Answers (2)

Update! I ended up using $(document).height() instead of scrolltop, because it allowed me to introduce a percentage easily. So my code ended up looking like this:

$(window).scroll(function () { 
    if ($(this).scrollTop() > 445) { 
        nav.addClass("f-nav");
    if ($(this).scrollTop() > $(document).height()*0.64) 
        nav.removeClass("f-nav");
    }       
});

Anyways, thanks for the help and I hope someone can find this useful!

Upvotes: 1

scraaappy
scraaappy

Reputation: 2886

From the doc, scrollTop() expects a number which represents position in pixel.

But you can calculate when scroll reaches 80% with, for example, something like

Pseudo-code:

if ((this.scrollTop + this.height) / content.height >= .8){
// do something
}

See the working snippet below for example

$("#container").scroll(function () { 
    if (($(this).scrollTop()+$(this).height())/$("#content").height() >= .8) { 
        $("#content").addClass("scrolled");
     }else{
       $("#content").removeClass("scrolled");
     }
     });
#container{
  width:80%;
  height:300px;
  border: solid 1px red;
  overflow:auto;
}

#content{
  width:80%;
  height:1000px;
  border: solid 1px gray;
  transition: background-color 1s;
}
#content.scrolled{
  background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="container">
  <div id="content"></div>
</div>

Upvotes: 7

Related Questions