Scrolltop does not work after certain scrolling

Asked

Viewed 100 times

2

I have a div calling for quest, I want that after the ScrollTop 100, he stays fixed.

Is not working.

var $w = $(window);

$w.on("scroll", function(){
   if( $w.scrollTop() > 100 ) {
        $('busca').css("position", "fixed");
   }
   else{
        $('busca').css("position", "static");
   }

});
  • Is there an error in the console? Try to take the value of scrollTop and give a console and see the result...

  • @Diegosantos includes the console.log in if and it came back right. console.log("Greater than 100");

  • 1

    Pera, your element does not call search... Not missing a point before? or a hashtag? Type $('#search'). css("position", "Fixed"); ???

  • 1

    Felipe think you can solve this only with CSS, unless you really want to use jQuery... If you want to put a simple example to do this with 5 CSS lines...

  • 1

    @Diegosantos was that yes.

  • @hugocsl can be yes

Show 1 more comment

2 answers

4


Your code has some errors first your search selector must be an ID or Class then it must be "#search" or ". search" second variable javascript does not have $ so the code should look like this

var w = $(window);

w.on("scroll", function(){
   if( w.scrollTop() > 100 ) {
        $('.busca').css("position", "fixed");
   }
   else{
        $('.busca').css("position", "static");
   }

});

EDIT

Maybe it works better this way by setting top:0 z-index one level above the others

    var w = $(window);

w.on("scroll", function(){
   if( w.scrollTop() > 100 ) {
        $('.busca').css({"position":"fixed", "top":"0px","z-index":"1"});
   }
   else{
        $('.busca').css({"position": "static"});
   }

});
  • 1

    Probably right!

  • You kicked and hit but he could be using a custom tag and the variable bid with $ does not influence anything. :/

1

As noted in the comment, and within what I understood of the question, I think this CSS example can help you if you don’t want to use jQuery etc.

In this example the element is 100px do topo, and when you give the scroll he will stop the 50px do topo. I left the comments in the code.

body {
    height: 200vh;
}
.teste {
    background-color: red;
    width: 100px;
    height: 50px;
    margin-top: 100px; /* altura que está do topo */
    top: 50px; /* altura que vai parar antes do topo */
    position: sticky;
}
<div class="teste"></div>

Browser other questions tagged

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