Since I'm working in Wordpress my sidebar is an element. This means it cannot be height: 100%
without making it position: absolute
which will break my CSS grid.
How can I make the sidebar behave like it's in position: sticky
by scrolling down with the user but stopping at the footer using jQuery/JS alone?
// Fixed Widget
function fixDiv() {
var $cache = $('.widget');
if ($(window).scrollTop() > 380)
$cache.css({
'position': 'fixed',
'top': '10px',
'right': '30px'
});
else
$cache.css({
'position': 'relative',
'top': 'auto',
'right': 'auto'
});
}
$(window).scroll(fixDiv);
fixDiv();
function stopDiv() {
var distance = $('.footer').offset().top - $('.widget').offset().top;
if (distance < 10) {
$('.widget').css({
'top': 'auto',
'bottom': '10px'
});
}
}
$(window).scroll(stopDiv);
stopDiv();
@import url('https://fonts.googleapis.com/css?family=Open+Sans:400,700');
* {
font-family: 'Open Sans';
color: #fff;
box-sizing: content-box;
}
body {
padding: 0;
margin: 0;
}
p {
margin: 20px;
}
hr {
width: 85%;
border-style: solid;
}
.main-content {
width: 100%;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 150px auto;
grid-template-areas: "nav nav nav nav" "main main main sidebar";
grid-column-gap: 20px;
grid-row-gap: 0px;
}
.nav {
grid-area: nav;
background-color: #266392;
display: grid;
grid-template-columns: 1fr 3fr 1fr;
}
.nav h1 {
place-self: center;
font-weight: 400;
font-size: 40px;
grid-column: 2;
}
.nav i {
align-self: center;
font-size: 40px;
}
.main {
height: 1500px;
width: 98%;
justify-self: start;
grid-area: main;
padding: 10px;
float: left;
background-color: #e8624c;
margin: 10px;
}
.sidebar-container {
height: 900px;
width: 300px;
justify-self: start;
background-color: #209B66;
grid-area: sidebar;
grid-column: 4;
top: 10px;
margin: 10px;
padding: 20px;
display: grid;
grid-template-rows: auto;
grid-row-gap: 10px;
}
.sidebar-container>p {
display: grid;
align-items: start;
padding: 0;
margin: 0;
}
.widget {
height: 500px;
width: 300px;
background-color: #E3962F;
}
.footer {
background-color: #333;
height: 800px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main-content">
<div class="nav">
<h1>Sticky Sidebar Problem</h1>
<i class="fa fa-arrow-down" aria-hidden="true"></i>
</div>
<div class="main">
<p>
[Main Content]
</p>
</div>
<div class="sidebar-container">
<p>[Sidebar Container]</p>
<div class="widget">
<p> [Widget]</p>
</div>
</div>
</div>
<div class="footer"></div>
</body>
This post is mostly code so I have to write some stuff so that it will let me post this edit so here is the text that I am writing so that I can just save and move on with my life please ignore this omg how much more do I have to type. Is this enough? How about this?