Created
July 14, 2017 11:25
-
-
Save sujeetkv/b0ba90cc7e700f333ec6ba5925e4873c to your computer and use it in GitHub Desktop.
stickyScroll: sticky horizontal scrollbar for x-scroll container.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function ($) { | |
$.fn.stickyScroll = function () { | |
var $this = this; | |
var scrollbar = $('<div id="fixed-scrollbar"><div></div></div>').appendTo($(document.body)); | |
scrollbar.hide().css({ | |
overflowX: 'auto', | |
width: '100%', | |
position: 'fixed', | |
bottom: 0 | |
}); | |
var fakecontent = scrollbar.find('div'); | |
var active = $([]); | |
var lastScroll; | |
function top(elem) { | |
return elem.offset().top; | |
} | |
function bottom(elem) { | |
return elem.offset().top + elem.height(); | |
} | |
function fit(active) { | |
if (!active.length) { | |
return scrollbar.hide(); | |
} | |
scrollbar.css({left: active.offset().left, width: active.width()}); | |
fakecontent.width($(this).get(0).scrollWidth); | |
fakecontent.height(1); | |
delete lastScroll; | |
} | |
function find_active() { | |
scrollbar.show(); | |
var active = $([]); | |
$this.each(function () { | |
if (top($(this)) < top(scrollbar) && bottom($(this)) > bottom(scrollbar)) { | |
fakecontent.width($(this).get(0).scrollWidth); | |
fakecontent.height(1); | |
active = $(this); | |
} | |
}); | |
fit(active); | |
return active; | |
} | |
function scroll() { | |
if (!active.length) { | |
return; | |
} | |
if (scrollbar.scrollLeft() === lastScroll) { | |
return; | |
} | |
lastScroll = scrollbar.scrollLeft(); | |
active.scrollLeft(lastScroll); | |
} | |
function update() { | |
if (!active.length) { | |
return; | |
} | |
if (active.scrollLeft() === lastScroll) { | |
return; | |
} | |
lastScroll = active.scrollLeft(); | |
scrollbar.scrollLeft(lastScroll); | |
} | |
function onscroll() { | |
var oldactive = active; | |
active = find_active(); | |
if (oldactive.not(active).length) { | |
oldactive.unbind('scroll', update); | |
} | |
if (active.not(oldactive).length) { | |
active.scroll(update); | |
} | |
update(); | |
} | |
scrollbar.scroll(scroll); | |
onscroll(); | |
$(window).scroll(onscroll); | |
$(window).resize(onscroll); | |
return $this; | |
}; | |
})(jQuery); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function () { | |
$('.container').stickyScroll(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment