I have a fixed sidebar, which is visible all along the page when scrolling down.
The problem is that - in some cases - the sidebar is getting over the footer when reaching to the bottom of the page.
I want to hide the sidebar when the Footer is visible on screen to avoid that. How can I do it?
Approach: Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element.
Add a padding top on the #scrollable div and make the #menu div absolute. Add a z-index to the #menu div so it stays on top. Also, make sure to add box-sizing: border-box on all elements to prevent exceeding the assigned sizes. Save this answer.
The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
Try this:
var isScrolledIntoView = function(elem) {
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).on('scroll', function () {
$('#sidebar').toggle(!isScrolledIntoView('#footer'));
});
Reference: Check if element is visible after scrolling
The function is called on window scroll and check if footer
is visible.
If visible, it hides sidebar
else shows.
well... this is what I ended up with - works like a charm :)
$.fn.isVisible = function() {
// Current distance from the top of the page
var windowScrollTopView = $(window).scrollTop();
// Current distance from the top of the page, plus the height of the window
var windowBottomView = windowScrollTopView + $(window).height();
// Element distance from top
var elemTop = $(this).offset().top;
// Element distance from top, plus the height of the element
var elemBottom = elemTop + $(this).height();
return ((elemBottom <= windowBottomView) && (elemTop >= windowScrollTopView));
}
$(document).ready(function() {
$(window).scroll(function() {
if($("#footer").isVisible()) {
$("#sidebar").addClass('hiddensidebar');
} else {
$("#sidebar").removeClass('hiddensidebar');
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With