JSFiddle - React, Tailwind, and code Playground
HTML
some intro
<div class="fixed-scrollbar-container">
<pre class="div2">
aaaa bbbb cccc dddd aaaa bbbb<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>><br/><br/><br/><br/><br/><br/><br/><br/><br/>><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd 12123141 1231 1231 23 12
</pre>
</div>
outside of the world
<div class="fixed-scrollbar-container">
<pre class="div2"> and again!
aaaa bbbb cccc dddd aaaa bbbb<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>><br/><br/><br/><br/><br/><br/><br/><br/><br/>><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd aaaa bbbb cccc dddd 12123141 1231 1231 23 12
</pre>
</div>
and bye!
CSS
.fixed-scrollbar-container {
overflow:auto;
background:lightgreen;
}
JavaScript
$(function($){
var fixedBarTemplate = '<div class="fixed-scrollbar"><div></div></div>';
var fixedBarCSS = { display: 'none', overflowX: 'scroll', position: 'fixed', width: '100%', bottom: 0 };
$('.fixed-scrollbar-container').each(function() {
var $container = $(this);
var $bar = $(fixedBarTemplate).appendTo($container).css(fixedBarCSS);
$bar.scroll(function() {
$container.scrollLeft($bar.scrollLeft());
});
$bar.data("status", "off");
});
var fixSize = function() {
$('.fixed-scrollbar').each(function() {
var $bar = $(this);
var $container = $bar.parent();
$bar.children('div').height(1).width($container[0].scrollWidth);
$bar.width($container.width()).scrollLeft($container.scrollLeft());
});
};
$(window).on("load.fixedbar resize.fixedbar", function() {
fixSize();
});
var scrollTimeout = null;
$(window).on("scroll.fixedbar", function() {
clearTimeout(scrollTimeout);
scrollTimeout = setTimeout(function() {
$('.fixed-scrollbar-container').each(function() {
var $container = $(this);
var $bar = $container.children('.fixed-scrollbar');
if($bar.length) {
var containerOffset = {top: $container.offset().top, bottom: $container.offset().top + $container.height() };
var windowOffset = {top: $(window).scrollTop(), bottom: $(window).scrollTop() + $(window).height() };
if((containerOffset.top > windowOffset.bottom) || (windowOffset.bottom > containerOffset.bottom)) {
if($bar.data("status") == "on") {
$bar.hide().data("status", "off");
}
} else {
if($bar.data("status") == "off") {
$bar.show().data("status", "on");
$bar.scrollLeft($container.scrollLeft());
}
}
}
});
}, 50);
});
$(window).trigger("scroll.fixedbar");
});