Div doesn’t stick to the top?

Asked

Viewed 60 times

4

I have a div that I would like you to hold to the top when the div has to touch the top. I tried to do this, resulted but the div continuous 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 stays fixed, will be the same distance from the top as the scroll, so it will always be stuck to the top. There is how to save the old position?

2 answers

2

I figured out how to solve. Instead of loading the position of <div> menu, load it out of the function of the scroll, I mean, 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");
  }
});

0


You can do it this way 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>
Role a página
<br /><br />
<div class="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 />

  • Thank you for your reply! Perfect and functional example.

  • @I_like_trains Thanks my dear! Success!

Browser other questions tagged

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