Anyone know how to make the verticle scrollbar appear only when scrolling with CSS or JS?
Thanks
To scroll only horizontally, we need to use the overflow-x property as we mentioned above and set the width and border properties. Also, we add a <p> element inside the <div> tag and then add style to it in the CSS section.
Use overflow: auto . Scrollbars will only appear when needed. (Sidenote, you can also specify for only the x, or y scrollbar: overflow-x: auto and overflow-y: auto ).
For vertical scrollable bar use the x and y axis. Set the overflow-x:hidden; and overflow-y:auto; that will automatically hide the horizontal scroll bar and present only vertical scrollbar. Here the scroll div will be vertically scrollable.
This can be done using CSS or JavaScript/jQuery.
// JavaScript Example
document.querySelector('.jsExample').addEventListener('mouseenter', function(e){
e.target.style.overflow = 'auto';
}, false);
document.querySelector('.jsExample').addEventListener('mouseleave', function(e){
e.target.style.overflow = 'hidden';
}, false);
// jQuery Example
$('.jQueryExample').hover(
function() { // Run on hover/mouseenter
$(this).css('overflow', 'auto');
},
function() { // Run on mouseleave
$(this).css('overflow', 'hidden');
}
);
/* CSS Example */
.cssExample { overflow: hidden; }
.cssExample:hover { overflow: auto; }
/* Unimportant CSS just to setup examples */
.cssExample, .jsExample, .jQueryExample {
background: #EEE;
box-sizing: border-box;
height: 4em;
width: 300px;
padding: 0.5em 1em;
margin-bottom: 1em;
overflow: hidden;
}
.cssExample::after, .jsExample::after, .jQueryExample::after {
display: block;
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cssExample">CSS Example</div>
<div class="jsExample">JavaScript Example</div>
<div class="jQueryExample">jQuery Example</div>
With the JavaScript or jQuery versions you could do more stuff like showing a custom scrollbar or attach the hover event listener to an element that covers the right 100px of the scrolling element so that the scroll bar only appears when the mouse moves to that side. Just a couple of examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With