Reputation: 4045
I have the following code:
var footer = $('.footer'),
extra = 0;
// footer.css({ opacity: '0', display: 'block' });
$(window).scroll(function() {
var scrolledLength = ( $(window).height() + extra ) + $(window).scrollTop(),
documentHeight = $(document).height();
console.log( 'Scroll length: ' + scrolledLength + ' Document height: ' + documentHeight )
if( scrolledLength >= documentHeight ) {
footer
.addClass('bottom')
// .slideUp();
.stop().animate({ bottom: '0', opacity: '1' }, 300);
}
else if ( scrolledLength <= documentHeight && footer.hasClass('bottom') ) {
footer
.removeClass('bottom')
// .slideDown();
.stop().animate({ bottom: '-100', opacity: '0' }, 300);
}
});
My goal is to show the footer once the user scrolls to the bottom of the page. If the user scrolls up again, I want the footer to slide down again.
Right now I am checking the scrolledLength
against the documentHeight
. However, the problem seems to be that the documentHeight
changes once we reach the bottom, since the footer appears and the extends the document.
My code does work, the footer does not disappear again or anything, but it is flickering a lot (and then eventually calms down), as it is being calculated anew. How could i solve this? Are there any mistakes in my code?
Upvotes: 1
Views: 1557
Reputation: 13385
You are already adding a class to the footer, the animation can be handled using CSS:
.footer {
position: fixed;
width: 100%;
height: 100px;
bottom: -100px;
transition: all 200ms ease-out;
}
.footer.bottom {
bottom: 0;
}
Update: JSFiddle with working slide up footer.
Obviously I'm guessing at how the footer should by styled since you haven't provided the CSS - this code will simply animate the footer up when the class .bottom
is added.
Upvotes: 1
Reputation: 1454
Try to use css transition instead:
var footer = $('.footer'),
extra = 0;
// footer.css({ opacity: '0', display: 'block' });
$(window).scroll(function() {
var scrolledLength = ( $(window).height() + extra ) + $(window).scrollTop(),
documentHeight = $(document).height();
if( scrolledLength >= documentHeight ) {
footer
.addClass('open')
}
else if ( scrolledLength <= documentHeight && footer.hasClass('open') ) {
footer
.removeClass('open')
}
});
.container{
position:relative;
height: 200vh;
width:100%;
background-color:red;
overflow:hidden;
}
.footer{
height: 100px;
width:100%;
position: absolute;
left:0px;
bottom:-100px;
background-color: black;
transition: 1s;
}
.open{
bottom:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="footer"></div>
</div>
Upvotes: 1