-1

I have and element classed .root-body it contain all page content and it scroll instead of <body>. I want to toggle a class to my page .navigation when user scroll inside the .root-body

HTML

<body>
    <div class="navigation"></div>
    <div class="root-body">
        <!-- page content goes here -->
    </div>
</body>

CSS

body {
    overflow: hidden;
}
.root-body {
    width: 100vw;
    height: 100vh;
    overflow: scroll;
}
Cristiano Soares
  • 619
  • 1
  • 9
  • 20

1 Answers1

0

Using $().on('scroll', ...) you can listen to the scroll event in certain element, as shown below. Then you can use addClass method to add the class you want and removeClass to remove it.

$(document).ready(function() {
    'use strict';
    $(".root-body").on('scroll', evt => {
      if($(evt.target).scrollTop() > 1){
        $(".navigation").addClass('bg-red');
      } else {
        $(".navigation").removeClass('bg-red');
      }
    })
})
body {
 overflow: hidden;
}

.root-body {
    width: 100px;
    height: 100px;
    overflow: scroll;
}

.navigation {
  height: 20px;
  width: 100px;
}

.bg-red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="navigation"></div>
<div class="root-body">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. Rem culpa laboriosam aut dignissimos, labore nemo, at incidunt voluptas dicta totam iusto, debitis neque explicabo! Nulla soluta officia earum ratione tenetur!
</div>
Cristiano Soares
  • 619
  • 1
  • 9
  • 20
  • @RoryMcCrossan, thanks for your feedback. I've just improved my answer. – Cristiano Soares Feb 15 '19 at 17:35
  • Couple notes - if you only want to add the class once, then use `$(".root-body").one('scroll',..`. Otherwise you might want to check the scroll position and remove the class if 0 (not in OPs question, just expanding to the next step). If doing anything other than a simple add class with colour, you might like to `debounce` the scroll event as it first a lot. – freedomn-m Feb 15 '19 at 17:48
  • Thanks for you It's working, Just one thing I missed: I want to add class when user scroll 1px to bottom and remove the class when user go to the top of the element. – rateb crypto Feb 15 '19 at 17:51
  • @ratebcrypto, I've improved my code to show how you can achive what you want. In this case you need to use `scrollTop` method to check the `scrollPosition` of the element. – Cristiano Soares Feb 15 '19 at 17:58