I'm currently working on adapting a method to make elements "sticky" for older browsers as discussed in this particular article.
The basic idea involves implementing some JavaScript code that listens for scroll events. Upon detection of such an event, it applies the style rule position: fixed
to the specified element to keep it in place while the user scrolls. To prevent any disruption in the page layout when the element becomes fixed, an identically sized div is inserted before the fixed element.
While this approach works well in general, I've encountered difficulties getting it to function properly on my web page due to my attempt to fix a right-hand div within a two-column layout. Despite setting the width of the element to match the sticky element, the menu shifts to the left once it becomes "stuck".
The CSS classes used for positioning the right-hand column are as follows:
.objects {
margin: 10px 30px;
float: right;
display: inline-block;
text-align: center;
top: 30px;
width: 40%;
}
.objects .content-block {
margin: 0px;
width: 100%;
}
<div class="objects" id="sticky">
<div class="content-block">
</div>
</div>
Here is the JavaScript code being employed:
var menu = document.querySelector('#sticky');
var menuPosition = menu.getBoundingClientRect();
var placeholder = document.createElement('div');
placeholder.style.width = menuPosition.width + 'px';
var isAdded = false;
document.getElementById("content").addEventListener('scroll', function() {
if (document.getElementById("content").scrollTop >= menuPosition.top && !isAdded) {
menu.classList.add('sticky');
menu.parentNode.insertBefore(placeholder, menu);
isAdded = true;
} else if (document.getElementById("content").scrollTop < menuPosition.top && isAdded) {
menu.classList.remove('sticky');
menu.parentNode.removeChild(placeholder);
isAdded = false;
}
});
Interestingly, adjusting the width of the "placeholder" element doesn't seem to have any effect.
A detailed description of the issue can be found in this provided fiddle.
I'm seeking guidance on what changes need to be made in the CSS to ensure that the element stays in its original position within the right-hand column.