Trying to achieve this task may seem quite unusual :)
However, here is the issue at hand:
When you apply the position: fixed
property to your inner div
, it ends up overlapping your div.right
and preventing scrolling events from occurring.
To resolve this, you can add pointer-events: none
to the div.scroll
so that your div.right
can continue to listen for scroll events without interference.
Yet, implementing this solution introduces a new challenge - setting your div.scroll
to position: fixed
causes it to lose its position within the div.right
, causing the latter to jump to the top of the scroll automatically. To counteract this, you must create a clone of the div.scroll
, initially setting its height to 0
and then changing it to auto
when the inner element becomes fixed.
Note: Using pointer-events: none
disables all mouse events, including text selection.
Here is the necessary code snippet:
JavaScript
$(document).ready(function() {
var container = $('.right');
var scrollElement = $('.scroll');
var clonedScrollElement = scrollElement.clone().addClass('clone');
scrollElement.before(clonedScrollElement);
container.scroll(function() {
var condition = clonedScrollElement.offset().top <= 0;
scrollElement.toggleClass('stick', condition);
clonedScrollElement.toggleClass('stick-clone', condition);
});
})
CSS
.scroll {
background: yellow;
pointer-events: none;
overflow: hidden; /* Remove top offset from h1*/
}
.scroll.stick {
position: fixed;
left: 20px;
right: 0;
top: 0;
}
.scroll.clone {
height: 0;
overflow: hidden;
}
.scroll.clone.stick-clone {
height: auto;
}
JSFiddle Link