javascript - How can I create a simple page vertical scroll bar without using jQuery? -


i have looked @ think scrollbars code have not yet been able find simple 1 not use jquery or complex library.

has created there own simple scrollbar using javascript? looking example of how can done. in particular have simple bootstrap web page with:

<body>    <header> ....</header>    <main> ......</main> </body> 

what able have small in page scroll bar appear right of area if content there larger fit on single page. styling purposes not browser default scroll bar.

here's example of looking 1 use jquery cannot use on site:

http://manos.malihu.gr/repository/custom-scrollbar/demo/examples/complete_examples.html

i looking way using javascript in modern browser ie9 , above. think useful many people have opened bounty of 200 in hope provide example of draggable page scrollbar respond mousewheel when on page content area.

just update. not looking mobile solution this. looking solution work inside pc / mac browser. site not set or suitable phone. it's possible use on ipad / tablet needs able have scrollbar default use normal tablet scrolling method.

surprisingly, there not great, simple solution out there using vanilla javascript. made pure js lightweight, minimal cross browser solution. adjust own needs , aesthetics

update include draggable scroll:
here fiddle , codepen

html

<body>     <div id="main" class="scrollable">         <div class="content-wrapper">             <div class="content">                 <p>lorem ipsum dolor sit amet, consectetur adipisicing elit. incidunt accusamus maxime voluptatem quasi. recusandae optio nobis ratione iste consectetur consequatur cupiditate saepe laborum natus neque provident eum explicabo delectus qui accusantium nostrum reiciendis soluta hic ut @ sed laboriosam possimus repudiandae deserunt velit rerum. aliquam ratione itaque corrupti aperiam quisquam unde aspernatur odio id repellendus corporis eaque expedita in ab minus possimus! quo tempore consequatur repellat consectetur nemo molestiae perferendis ipsum esse nesciunt blanditiis nobis dicta? laudantium quaerat inventore deleniti exercitationem explicabo quos pariatur sunt earum labore sed eius blanditiis architecto consequuntur ad consectetur unde sapiente nisi. sunt eos.</p>                 <p>lorem ipsum dolor sit amet, consectetur adipisicing elit. incidunt accusamus maxime voluptatem quasi. recusandae optio nobis ratione iste consectetur consequatur cupiditate saepe laborum natus neque provident eum explicabo delectus qui accusantium nostrum reiciendis soluta hic ut @ sed laboriosam possimus repudiandae deserunt velit rerum. aliquam ratione itaque corrupti aperiam quisquam unde aspernatur odio id repellendus corporis eaque expedita in ab minus possimus! quo tempore consequatur repellat consectetur nemo molestiae perferendis ipsum esse nesciunt blanditiis nobis dicta? laudantium quaerat inventore deleniti exercitationem explicabo quos pariatur sunt earum labore sed eius blanditiis architecto consequuntur ad consectetur unde sapiente nisi. sunt eos.</p>             </div>         </div>     </div>     <div>not special , not contained within scrolling</div> </body> 

css

.scrollable {     padding: 0% 10%;     position: relative;     border: 1px solid gray;     overflow: hidden;     height: 400px; }  .scrollable.showscroll::after {     position: absolute;     content: '';     top: 5%;     right: 7px;     height: 90%;     width: 3px;     background: rgba(224, 224, 255, .3); }  .scrollable .content-wrapper {     width: 100%;     height: 100%;     padding-right: 50%;     overflow-y: scroll; } .scroller {     z-index: 5;     cursor: pointer;     position: absolute;     width: 10px;     border-radius: 5px;     background: rgb(111, 111, 190);     top: 0px;     right: 3px;     -webkit-transition: top .08s;     -moz-transition: top .08s;     -ms-transition: top .08s;     -o-transition: top .08s;     transition: top .08s; } .content {     -webkit-touch-callout: none;     -webkit-user-select: none;     -khtml-user-select: none;     -moz-user-select: none;     -ms-user-select: none;     user-select: none; } 

js

(function () {  var scrollcontainer = document.queryselector('.scrollable'),     scrollcontentwrapper = document.queryselector('.scrollable .content-wrapper'),     scrollcontent = document.queryselector('.scrollable .content'),     contentposition = 0,     scrollerbeingdragged = false,     scroller,     topposition,     scrollerheight;  function calculatescrollerheight() {     // *calculation of how tall scroller should     var visibleratio = scrollcontainer.offsetheight / scrollcontentwrapper.scrollheight;     return visibleratio * scrollcontainer.offsetheight; }  function movescroller(evt) {     // move scroll bar top offset     var scrollpercentage = evt.target.scrolltop / scrollcontentwrapper.scrollheight;     topposition = scrollpercentage * (scrollcontainer.offsetheight - 5); // 5px arbitrary offset scroll bar doesn't move far beyond content wrapper bounding box     scroller.style.top = topposition + 'px'; }  function startdrag(evt) {     normalizedposition = evt.pagey;     contentposition = scrollcontentwrapper.scrolltop;     scrollerbeingdragged = true; }  function stopdrag(evt) {     scrollerbeingdragged = false; }  function scrollbarscroll(evt) {     if (scrollerbeingdragged === true) {         var mousedifferential = evt.pagey - normalizedposition;         var scrollequivalent = mousedifferential * (scrollcontentwrapper.scrollheight / scrollcontainer.offsetheight);         scrollcontentwrapper.scrolltop = contentposition + scrollequivalent;     } }  function createscroller() {     // *creates scroller element , appends '.scrollable' div     // create scroller element     scroller = document.createelement("div");     scroller.classname = 'scroller';      // determine how big scroller should based on content     scrollerheight = calculatescrollerheight();      if (scrollerheight / scrollcontainer.offsetheight < 1){         // *if there need have scroll bar based on content size         scroller.style.height = scrollerheight + 'px';          // append scroller scrollcontainer div         scrollcontainer.appendchild(scroller);          // show scroll path divot         scrollcontainer.classname += ' showscroll';          // attach related draggable listeners         scroller.addeventlistener('mousedown', startdrag);         window.addeventlistener('mouseup', stopdrag);         window.addeventlistener('mousemove', scrollbarscroll)     }  }  createscroller();   // *** listeners *** scrollcontentwrapper.addeventlistener('scroll', movescroller); }()); 

the concept simple. have main div 'scrollable' class. javascript recognizes element , appends scroller div can style css. nesting content-wrapper child div can push native scroller outside of parent div while still controlling padding.

here diagram: scroll diagram

the reason need maintain native scrolling ability because javascript scroll event fires on elements have overflow set scroll. see mdn reference on scroll. benefit being if js disabled, still gracefully fallback scrolling without scrollbar.


note
should note have adjust version recalculate scroller size in cases:
1.) screen resized or
2.) if more content appended.

secondly, modifications have made if have multiple 'scrollable' elements. in case, need loop on elements both append scroller div , listen scroll event.


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -