Question :
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?
Answer :
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 />
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");
}
});