Search code examples
javascriptjqueryhtmlscrollscrolltop

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.


Solution

  • 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>