ScrollTop does not work after some scrolling

2

I have a div called search , I want that after ScrollTop 100 , it stays fixed.

Not working.

var $w = $(window);

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

});
    
asked by anonymous 10.04.2018 / 19:14

2 answers

4

Your code has some errors first your search selector must be an ID or Class then it should be "#search" or ".search" second variables in javascript do not have $ then the code should stay 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 by setting top: 0 z-index one level above the rest

    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"});
   }

});
    
10.04.2018 / 20:06
1

As mentioned in the comment, and within what I understood the question, I think this CSS example can help you if you do not want to use jQuery etc.

In this example the element is 100px do topo , and when you give scroll it will stop 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>
    
10.04.2018 / 20:06