Div does not hold the top?

4

I have div that I would like it to hold at the top when the div has to play at the top. I tried to this , but resulted in% blinking%%. What's wrong?

SCRIPT

$(window).on('scroll', function() {
  var ell = $('.menu').offset().top;
  var ill = $(document).scrollTop();
  var screen = $(window).height();
  var distance = ell - ill;
  if(ell < ill ) {
      $('.menu').css("position", "fixed");
      $('.menu').css("top", "0");
  }else{
    $('.menu').css("position", "relative");
    $('.menu').css("top", "initial");
  }
});

UPDATE

I discovered the problem, since the div is div , will be the same distance from the top as the scroll, so it will always be stuck to the top. Is there a way to save the old position?

    
asked by anonymous 30.10.2017 / 16:54

2 answers

0

You can do this too:

$(window).on('scroll', function() {
  var ell_height = $('.menu').outerHeight(); // pego altura da div para os cálculos
  var ell = $('.menu').offset().top;
  var ill = $(window).scrollTop();
//  var screen = $(window).height();
  var distance = ell-ill;
  if(distance <= 0 && ill > ell_height) {
      $('.menu').css({
		  "position":"fixed",
		  "top":"0"
	  })
	  .text("div posição fixa");
  }else if(ill <= ell_height){
    $('.menu')
	.css("position", "relative")
	.text("div posição normal");
  }
});
.menu{
	display: block; background: red; width: 200px; height: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Roleapágina<br/><br/><divclass="menu">
	div posição normal
</div>
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
<br /><br /><br /><br /><br /><br />
    
30.10.2017 / 17:35
2

I found out how to solve. Instead of loading the position of <div> menu , I load it out of the function of scroll , that is, the code would look like this

var ell = $('.menu').offset().top;
$(window).on('scroll', function() {
  var ill = $(document).scrollTop();
  var dif = ill - ell;
   $(".menu").html("Distância Menu: "+ell+"     |    Distância Scroll: "+ill+"     |    Diferença: "+dif);

  if(dif >= 0  ) {
      $('.menu').css("position", "fixed");
      $('.menu').css("top", "0");
  }else{
    $('.menu').css("position", "relative");
    $('.menu').css("top", "initial");
  }
});
    
30.10.2017 / 17:21