Author: | Vaibhav Arora |
---|---|
Views Total: | 112 views |
Official Page: | Go to website |
Last Update: | April 25, 2018 |
License: | MIT |
Preview:

Description:
This is a dynamic vertical scroller with section indexing feature, written in JavaScript and CSS. Great for contact list.
Similar to the Android & Material Design RecyclerView that displays an alphabets bubble following the scrollbar.
How to use it:
Create the HTML for the scroller.
<div id="container" class="hideText"> <div id="scroll-display"> </div> <ul id="list"> </ul> </div>
Prepare your data to be presented in the scroller.
var aNames = [ { name: "Kamal" }, { name: "Perry" }, { name: "Ishmael" }, // ... ]
The main JavaScript to activate the scroller.
// Sorting names aNames = aNames.sort(function(oName1, oName2) { return oName1.name > oName2.name ? 1 : -1; }); // Make rows var oList = document.querySelector("#list"); for (var iIndex = 0; iIndex < 100; iIndex++) { var oItem = document.createElement("li"); oItem.innerText = aNames[iIndex].name; oList.appendChild(oItem); } var iItemHeight = 40; // Caching children var aChildren = oList.querySelectorAll("li"); var oDisplay = document.querySelector("#scroll-display"); var oContainer = document.querySelector("#container"); var hideFn = null; oList.addEventListener("scroll", function() { oContainer.classList.remove("hideText"); var iScrollTop = oList.scrollTop; var iScrollHeight = oList.scrollHeight; var iHeight = oList.clientHeight; var currentItem = Math.floor(iScrollTop / iItemHeight); oDisplay.setAttribute("data-value", aChildren[currentItem].innerText.charAt(0)); oDisplay.style.transform = `translateY(${( (iScrollTop * iHeight) / iScrollHeight)}px)`; // Debounce hiding if(hideFn){ clearTimeout(hideFn); } hideFn = setTimeout(function() { oContainer.classList.add("hideText"); }, 200); });
The example CSS.
#list { height: 300px; display: flex; flex-direction: column; list-style: none; padding-left: 0px; margin: 0px; overflow-y: auto; } #list li { background: white; padding: 10px 20px; margin: 2px; } #scroll-display { position: relative; will-change: transform; } #scroll-display:after { border-radius: 30px; width: 15px; text-align: center; height: 15px; content: attr(data-value); position: absolute; top: 0; right: 20px; background: rgba(0, 0, 0, 0.7); color: white; padding: 10px; font-family: Courier; } #container.hideText #scroll-display { display: none; }