My web page has 3 divs. I have made the 2nd div sticky. My expectation was that when I scroll div1 would scroll off the top, div2 would stick when it reaches the top, and then div3 would scroll over div2 and off the top leaving div2 still stuck in place. Instead what actually happens is that when div3 reaches the top it and div2 both scroll off the top together.
Can anyone suggest a way to accomplish what I want?
Regarding the example code: Use the checkbox to make div2's position be either sticky or relative like the others.
window.onload = function() {
$('#divGroup2Sticky').change(function() {
let divName = 'divGroup2'
let div = $(`#${divName}`)
if (this.checked) {
div.css('position', 'sticky')
div.css('top', '1vh')
div.css('left', 'auto')
}
else {
div.css('position', 'relative')
div.css('top', '0px')
div.css('left', '0px')
}
})
}
html {
height: 500vh;
}
body {
background-color: gray;
}
.divGroup {
position: relative;
margin-top: 1vh;
margin-left: 1vh;
width: 98vw;
height: 98vh;
background-color: darkgray;
border: solid red 1px;
}
.innerDiv {
position: absolute;
top: 50%;
left: 50%;
translate: -50% -50%;
width: 80%;
height: 80%;
}
p {
margin: 0;
font-size: 25px;
text-align: center;
}
#checkbox {
position: fixed;
top: 2vh;
left: 2vw;
background-color: #D3D3D3;
border: 1px solid black;
border-radius: 5px;
padding: 4px;
z-index: 3;
}
<head>
<link rel='stylesheet' type='text/css' href='style.css' />
<script src="javascript.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
<div id="checkbox">
<input class="checkboxes" id="divGroup2Sticky" type="checkbox">
<label for="divGroup2Sticky">Div Group 2 Sticky</label>
</div>
<div id="divGroup1" class="divGroup">
<p>Div Group 1</p>
<div class="innerDiv" style="border: solid black 1px">
<div class="innerDiv" style="border: solid yellow 1px">
<div class="innerDiv" style="border: solid brown 1px">
</div>
</div>
</div>
</div>
<div id="divGroup2" class="divGroup">
<p>Div Group 2</p>
<div class="innerDiv" style="border: solid purple 1px">
<div class="innerDiv" style="border: solid orange 1px">
<div class="innerDiv" style="border: solid green 1px">
</div>
</div>
</div>
</div>
<div id="divGroup3" class="divGroup">
<p>Div Group 3</p>
<div class="innerDiv" style="border: solid turquoise 1px">
<div class="innerDiv" style="border: solid fuchsia 1px">
<div class="innerDiv" style="border: solid maroon 1px">
</div>
</div>
</div>
</div>
</body>
The solution to your problem is setting height of the body to 100%. Reason for this is that parent container of sticky element must have a defined height. Even tho height of html is set to 500vh the parent element of your div is body so body has to have defined height in order for div2 to be sticky.