Ways to display scroll bar when hovering the mouse pointer?

When visiting the website YouTube, you may notice that their sidebar scrollbar becomes visible as soon as your mouse moves over it. I've been attempting to achieve this effect on my own div, but currently, the scrollbar only appears once I start scrolling.

I have used overflow-y: auto;, and also experimented with overflow-y: scroll;, yet both options resulted in the same delayed visibility of the scrollbar.

Any suggestions on how to display the scrollbar immediately upon hovering or clicking?

Answer №1

Give this method a shot, it may offer some assistance to you.

Although it may not seem very promising at first glance, I believe it has the potential to work. Utilizing the scroll event, you can adjust it to your needs by utilizing the wheel event and setting the time delay accordingly.

(function () {
            var timer;
            document.querySelector('div').addEventListener('scroll', function (event) {
                if (event.type == 'scroll') {
                    addCSS = document.createElement('style');
                    addCSS.innerHTML = "::-webkit-scrollbar { display: block; }";
                    document.body.append(addCSS);
                }
                clearTimeout(timer);
                timer = setTimeout(refresh, 300);
            });
            var refresh = function () {
                addCSS = document.createElement('style');
                addCSS.innerHTML = "::-webkit-scrollbar { display: none; }";
                document.body.append(addCSS);
            };
        })();
.customized-scrollbar {
            display: block;
            width: 10em;
            overflow: auto;
            height: 2em;
            margin: 10px;
        }
        ::-webkit-scrollbar {
            display: none;
        }

        .customized-scrollbar:hover::-webkit-scrollbar {
            /* display: block; */
            cursor: pointer;
        }

        /* Demonstrate a "mostly customized" scrollbar
        * (won't be visible otherwise if width/height is specified) */
        .customized-scrollbar::-webkit-scrollbar {
            width: 5px;
            height: 50px;
            /* background-color: #aaa; */
            background-color: transparent;
        }

        /* Add a thumb */
        .customized-scrollbar::-webkit-scrollbar-thumb {
            background: #000;
            height: 100px;


}
<div class="customized-scrollbar hidden-scrollbar" style="height:150px;background:red;width:200px;margin:0 auto;">
        Etiam sagittis sem sed lacus laoreet, eu fermentum eros auctor.
        Proin at nulla elementum, consectetur ex eget, commodo ante.
        Sed eros mi, bibendum ut dignissim et, maximus eget nibh. Phasellus
        blandit quam turpis, at mollis velit pretium ut. Nunc consequat
        efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
        sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
        tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
        consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
        amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
        mattis cursus dolor. Pellentesque id pretium est. Quisque
        convallis nisi a diam malesuada mollis. Aliquam at enim ligula
    </div>

Utilize the mouseover and mouseleave events for this implementation.

document.querySelector('div').addEventListener('mouseover', function (event) {
                addCSS = document.createElement('style');
                addCSS.innerHTML = "::-webkit-scrollbar { display: block; }";
                document.body.append(addCSS);


            });

             document.querySelector('div').addEventListener('mouseleave', function (event) {
             addCSS = document.createElement('style');
             addCSS.innerHTML = "::-webkit-scrollbar { display: none; }";
             document.body.append(addCSS);


             });
    html{
            scroll-behavior: smooth;
        }
        .customized-scrollbar {
            display: block;
            width: 10em;
            overflow: auto;
            height: 2em;
            margin: 10px;
        }
        ::-webkit-scrollbar {
            display: none;
            position: fixed;
           margin-right: -10px;
        }

        .customized-scrollbar:hover::-webkit-scrollbar {
            /* display: block; */
            cursor: pointer;
        }


        /* Demonstrate a "mostly customized" scrollbar
        * (won't be visible otherwise if width/height is specified) */
        .customized-scrollbar::-webkit-scrollbar {
            width: 5px;
            height: 50px;
            background-color: transparent;
        }

        /* Add a thumb */
        .customized-scrollbar::-webkit-scrollbar-thumb {
            background: #000;
            height: 100px;

}
<div class="customized-scrollbar hidden-scrollbar" style="height:150px;background:red;width:200px;margin:0 auto;">
        Etiam sagittis sem sed lacus laoreet, eu fermentum eros auctor.
        Proin at nulla elementum, consectetur ex eget, commodo ante.
        Sed eros mi, bibendum ut dignissim et, maximus eget nibh. Phasellus
        blandit quam turpis, at mollis velit pretium ut. Nunc consequat
        efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
        sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
        tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
        consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
        amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
        mattis cursus dolor. Pellentesque id pretium est. Quisque
        convallis nisi a diam malesuada mollis. Aliquam at enim ligula
</div>

Implement the hover effect:

.mostly-customized-scrollbar {
  display: block;
  width: 10em;
  overflow: auto;
  height: 2em;
  margin:10px;
}

.mostly-customized-scrollbar::-webkit-scrollbar {
  display: none;
}

.mostly-customized-scrollbar:hover::-webkit-scrollbar {
  display: block;
  cursor:pointer;
}

/* Demonstrate a "mostly customized" scrollbar
 * (won't be visible otherwise if width/height is specified) */
.mostly-customized-scrollbar::-webkit-scrollbar {
  width: 5px;
  height: 50px;
  background-color: transparent;
}

/* Add a thumb */
.mostly-customized-scrollbar::-webkit-scrollbar-thumb {
    background: #000; 
    height: 100px;
    
    
}
<div class="mostly-customized-scrollbar" style="height:150px;background:red;width:200px;margin:0 auto;">
Etiam sagittis sem sed lacus laoreet, eu fermentum eros auctor.
  Proin at nulla elementum, consectetur ex eget, commodo ante. 
  Sed eros mi, bibendum ut dignissim et, maximus eget nibh. Phasellus
  blandit quam turpis, at mollis velit pretium ut. Nunc consequat
  efficitur ultrices. Nullam hendrerit posuere est. Nulla libero
  sapien, egestas ac felis porta, cursus ultricies quam. Vestibulum
  tincidunt accumsan sapien, a fringilla dui semper in. Vivamus
  consectetur ipsum a ornare blandit. Aenean tempus at lorem sit
  amet faucibus. Curabitur nibh justo, faucibus sed velit cursus,
  mattis cursus dolor. Pellentesque id pretium est. Quisque
  convallis nisi a diam malesuada mollis. Aliquam at enim ligula
</div>

Answer №2

Give this a shot:

#box {
  padding: 10px;
  width: 200px;
  border: solid 1px blue;
  background-color: #f0f0f0;
}

#box:hover {
  border: solid 2px green;
}
<body>
  <div id="box">
    <p>Lorem ipsum</p>
    <p>Dolor sit amet</p>
  </div>
</body>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When setting a value through the DOM, the input's value bound with ngModel in Angular does not get updated

Trying to upload a file to calculate its hash and display it in an input box. If done correctly, the value should show in the form, but when submitting the form, the value does not get sent. Only adding a blank space by clicking on the input field works: ...

Retrieve the content from paginated pages using ajax, apply a filter to it, and then add it to the existing page

My blog needs more functionality and I want to avoid using paginated pages. My idea was to extract content from these paginated pages through ajax, filter it, and add it to a specific div element. I'm not completely confident if I am on the right tra ...

The TypeScript script does not qualify as a module

Just starting out with TypeScript and encountering a simple issue. I'm attempting to import a file in order to bring in an interface. Here's an example: Parent: import { User } from "@/Users"; export interface Gift { id: number; ...

Invoke a function in JavaScript just once using a closure

I have a JavaScript function that I want to call only once, using closure. Here's the code snippet: function initialize() { let called = 0; return function() { if (called > 0) { return } else { called++; console.log(&a ...

Navigate through two distinct elements by categorizing them based on their types

After completing the frontend design, I moved on to integrating the backend and encountered an issue. If anyone can offer assistance or even a hint, it would be greatly appreciated. Visit the demo website for more insight. Initially, I hard coded the comp ...

I just made an ajax call. Now, how should I proceed with formatting the data that was returned

The ajax request below is functional, but not without its challenges. Working with HttpContext has proven to be difficult, as even Context.Response.Clear() does not seem to have any effect. How can I output only the desired content without any extra infor ...

What could be causing the vertical alignment issue of this logo in its parent container?

I am having an issue with the vertical centering of the logo element within the <header> container on this page. It seems to be more pronounced on mobile devices compared to desktop. However, the second element (#forum-link) is aligning correctly. W ...

The battle of promises versus async await in Koa middleware

In an attempt to create a Koa middleware, I am faced with the decision of how to proceed based on certain conditions. If the condition is met, I want to move on to the next middleware. If it is not met, I need to stop the flow. Two possible approaches invo ...

Incorporating an external HTML page's <title> tag into a different HTML page using jQuery

I am faced with a challenge involving two files: index.html and index2.html. Both of these files reside in the same directory on a local machine, without access to PHP or other server-side languages. My goal is to extract the <title>Page Title</ ...

Attempting to create a single function that can be utilized with numerous divs that share the same class in jQuery

Currently, I am working on creating a basic jquery gallery viewer. In my code, I have the following structure: <div class="photoset"> <img /> <img /> </div> <div class="photoset"> <img /> <img /> <i ...

Can one customize the background color of a segment in a radar chart using Chart.js?

Could I customize the color of the sectors in my radar chart to resemble this specific image? https://i.stack.imgur.com/U8RAb.png Is it feasible to achieve this using Chart.js? Alternatively, are there other chart libraries that have this capability? It ...

Refreshing Angular Services: A Guide to Resetting Factories

My angular factory is quite intricate and structured like this: app.factory("mainFcty", function(){ return { a:"", b:"", c:"" } }); When users progress through the app and complete actions such as booking a service, they f ...

When the mouse leaves, the background image will revert back to its original setting

https://i.stack.imgur.com/Ojd0Q.pngI need assistance in reverting a div's background image back to its default state using the onmouseleave method. Below is the HTML and JS code I have been working on: <script type="text/javascript"> functi ...

Applying Styles to Cells Using the Google Sheets API (v4)

Having encountered an issue while using the Google Sheets API (v4) for programmatically creating or updating spreadsheets, I have come across the following problem: According to the documentation (https://developers.google.com/sheets/api/reference/rest/v4 ...

Adjusting the layering of a nested element within a container div using

I am facing an issue with two buttons placed within a container div that is being overlapped by another container div. The bottom container overlaps the top one, rendering the buttons unclickable. I have been trying to find a solution to make the buttons ...

error: "undefined property cannot be read"

I am encountering an issue on our site where a bot is needed to work properly. The error message I am receiving is "cannot read property ´value´ of undefined". I have already set the bind_address to 0.0.0.0, but that did not resolve the issue (I also tri ...

Import a 3-dimensional object from an .obj file and adjust its positioning within the camera view using Three.js

I am currently working on dynamically loading object files using THREE.OBJLoader and positioning them in the center of the scene or canvas to ensure the entire object is visible in the camera view. Since the objects are dynamic, I do not have fixed height ...

The issue of the selection option not being cleared after being set to 0 persists in JavaScript

I am facing an issue where I need to reset the select option to `0` when another option is selected. I have tried the code below for this purpose. if (varALPO1MobNum == "0") { var selectElement = $(&apo ...

What causes TypeScript's ReadonlyArrays to become mutable once they are transpiled to JavaScript?

Currently, I am in the process of learning Typescript by referring to the resources provided in the official documentation. Specifically, while going through the Interfaces section, I came across the following statement: TypeScript includes a special t ...

What is the ideal framerate for smooth animation?

I'm looking to add a snow animation using JavaScript. I currently have it running at 200ms which is decent but not smooth enough. Would changing the interval to 20ms make it more fluid, or would it be inefficient and strain the CPU? window.setInterva ...