What’s wrong with my Javascript scroll tag body code?

Asked

Viewed 63 times

0

Look at my personal code, my scroll is on the tag body, but it doesn’t work, I’ve done everything and nothing my scroll ta na < body > and still doesn’t work, what’s wrong ?

$(document.body).on("scroll", function(){
if($(document.body).scrollTop() > 10){
    $("#navbar").removeClass("fixed-bottom");
    $("#navbar").addClass("sticky-top");
    }else{
$("#navbar").removeClass("sticky-top");
    $("#navbar").addClass("fixed-bottom");
}});
  • Change document.body for window.

  • Opa Sam, all good ? Then I changed Document.body for Document.window and even then it didn’t work, I changed Document also just for window and nothing. Check out the page I’m moving: http://nexo.atspace.cc/Final . Nothing I do works :(

1 answer

1


Who scrolls the page is the object window, and not the body, unless you’ve put an overflow on the body with set height.

Your correct code would be:

$(window).on("scroll", function(){
   $("span").html("Scroll: "+$(this).scrollTop()); // só para ilustrar. Apague esta linha
   if($(this).scrollTop() > 10){
      $("#navbar").removeClass("fixed-bottom");
      $("#navbar").addClass("sticky-top");
   }else{
      $("#navbar").removeClass("sticky-top");
      $("#navbar").addClass("fixed-bottom");
   }
});
div{
   height: 2000px;
}

span{
   position: fixed;
   top: 10px;
   right: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Role pra baixo</div>
<span></span>

  • I got it Sam, I don’t know why he’s giving this, I saved it on the page and it’s like the code wasn’t there, he was supposed to change the navbar from bottom to top, but it doesn’t work, even with the changes made, but in my css it has the following style --> html{ overflow-y: scroll; scroll-behavior: Smooth; scroll-snap-type: y Mandatory; }

  • Is that where my problem lies ? I guess not because when I put a Function and an onscroll in the html tag it doesn’t work, but the body tag works, I don’t know why

  • Have you tried $("body")?

  • I tried it didn’t work, I’ll end up giving up and losing, but thank you very much Sam, you’re too good!

  • 1

    Things worked out here, thank you very much Sam

Browser other questions tagged

You are not signed in. Login or sign up in order to post.