Creating a blog site example and trying to lock the position of a div once it reaches the top of the page. Utilizing materialize.css for this task.
<div class="row">
<div class="col m8 s12">
<!-- content goes here -->
</div>
<div class="col s12 m4">
<div class="collection with-header" style="margin-top:3rem;">
<h5 class="collection-item">Trending topics</h5>
<a href="#" class="collection-item">Web design</a>
<a href="#" class="collection-item">Express framework</a>
<a href="#" class="collection-item">Cache API</a>
<a href="#" class="collection-item">Event handling in JavaScript</a>
<a href="#" class="collection-item">Django framework</a>
</div>
<!-- This div should be fixed after reaching the top -->
<div class="card-panel center" id="post-author" style="width:auto">
<div class="follow-author">
<img src="https://source.unsplash.com/random/200x200" alt="" class="responsive-img circle"
style="width:75px;">
<div class="blue-text darken-3">Ishaan Sheikh</div>
<small class="grey-text">@sheikh_i</small>
<div class="divider" style="margin:1rem 0;"></div>
<div class="grey-text">Follow Author </div>
<a href="#"><i class="fab fa-facebook"></i></a>
<a href="#"><i class="fab fa-twitter"></i></a>
<a href="#"><i class="fab fa-instagram"></i></a>
<a href="#"><i class="fab fa-github"></i></a>
</div>
</div>
</div>
</div>
Javascript code:
window.onscroll = function () {
myFunction();
};
var header = document.getElementById("post-author");
var sticky = header.offsetTop;
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
The sticky class definition:
.sticky {
position: fixed;
top: 0;
}
The issue encountered is that the fixed div width changes and shrinks unexpectedly. Seeking a solution for this problem which has been ongoing for the past couple of days.
Example can be viewed Here