Ruuji Hasegawa Ruuji Hasegawa - 7 months ago 14
HTML Question

"Scroll up button" not on window but on a certain div possible?

here is my question!

I have a scroll up button for a website, which activates itself after the user scrolls 50px down from

window
. In my case though the user scrolls in a div called
#pages
. I've tried to just replace the window in the jquery code but it doesn't seem to work. Any ideas?

The
.scrlTp
would be the button itself.

If the question isn't clear enough please ask, I would be more than thankful for your time!

My code right now:

$(document).ready(function(){

//Check to see if the window is top if not then display button
$(window).scroll(function(){
if ($(this).scrollTop() > 50) {
$('.scrlTp').fadeIn();
} else {
$('.scrlTp').fadeOut();
}
});

//Click event to scroll to top
$(window).click(function(){
$('html, body').animate({scrollTop : 0},800);
return false;
});

});

Answer

You'll have to replace html, body as well:

$(document).ready(function() {

  //Check to see if the window is top if not then display button
  $("#pages").scroll(function() {
    if ($(this).scrollTop() > 100) {
      $('.scrlTp').fadeIn();
    } else {
      $('.scrlTp').fadeOut();
    }
  });

  //Click event to scroll to top
  $(".scrlTp").click(function() {
    $("#pages").animate({
      scrollTop: 0
    }, 800);
    return false;
  });

});
#pages {
  height: 100px;
  width: 200px;
  overflow-y: scroll;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrlTp" style="display: none">to top</div>
<br />
<div id="pages">
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat fuga atque blanditiis nemo incidunt quibusdam obcaecati! Nisi ullam est provident corporis nesciunt excepturi iste ad, alias temporibus esse ipsum rerum!Lorem ipsum dolor sit amet, consectetur
  adipisicing elit. Dignissimos totam neque distinctio laborum cumque vitae, officiis architecto facilis accusamus quam consequatur tempora illo quia perferendis, alias autem magnam doloremque dolor!Lorem ipsum dolor sit amet, consectetur adipisicing
  elit. Magnam, quia amet beatae. Amet id labore dignissimos vitae libero, dolorum, quisquam laudantium, earum necessitatibus nostrum ex vel laborum eaque nesciunt facere.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Neque saepe quis consectetur
  explicabo natus nulla, provident voluptates placeat ipsam animi similique officia qui nihil, rerum earum ea deserunt ullam dolore!
</div>