Guide on creating CSS for webkit scrollbar through the use of Javascript

I have a div named 'dynamic' with text inside, and I am applying styling to it using javascript.

var styleElement = document.createElement("style");
styleElement.appendChild(document.createTextNode("#dynamic { color: red; }"));
document.getElementsByTagName("head")[0].appendChild(styleElement);

It is functioning properly. Similarly, I am attempting to add some CSS for the scrollbar, which can be achieved with the following CSS code:

div ::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 7px;
}

div ::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

Now, I have added it through javascript like this:

var styleElement = document.createElement("style");
styleElement.appendChild(document.createTextNode("
     div ::-webkit-scrollbar{
        -webkit-appearance: none;
         width: 7px;
     }
     div ::-webkit-scrollbar-thumb{
         border-radius: 4px;
         background-color: rgba(0,0,0,.5);
         -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
     }
"));
document.getElementsByTagName("head")[0].appendChild(styleElement);

Unfortunately, this is not producing the expected result.

My query is:

In the first scenario, adding color to the "dynamic" div using javascript worked fine. However, in the second scenario, while attempting to add CSS for the scrollbar using javascript, it is not working. If the first scenario worked, then the second scenario should work as well.

So, did I write it incorrectly or is there another way to add CSS for webkit-scrollbar using javascript?

Here is the code in jsFiddle

Answer №1

Having trouble styling scrollbars using javascript

The issue may not be with the javascript itself, try appending the styles to the head tag for compatibility with all javascript-enabled browsers.

Using the Pseudo element ::-webkit-scrollbar should work for Webkit browsers but not for Firefox (Gecko). For a similar discussion, check out this thread: Custom CSS Scrollbar for Firefox.

Feel free to test the code snippet below and observe the scrollbar color.

var styleElement = document.createElement("style");
styleElement.appendChild(document.createTextNode("div ::-webkit-scrollbar {-webkit-appearance: none;width: 7px;}div ::-webkit-scrollbar-thumb {border-radius: 4px;background-color: rgba(250,0,0,.5);-webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);}"));
document.getElementsByTagName("head")[0].appendChild(styleElement);
#container{
    width:500px;
    height:300px;
    background-color:#E0E0E0;
    position:relative;
}
#draggable{
    width:300px;
    height:200px;
    left:10px;
    top:20px;
    background-color:white;
    position:absolute;
    overflow:scroll;
}
<div id="container">
   <div id="draggable">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"</div>
</div>

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

I'm facing some uncertainties with a couple of AngularJS code snippets

At my workplace, I am tasked with making modifications to an angularjs project. However, I find the code quite complex and challenging to fully comprehend: app.controller("complementsController", function($scope, $rootScope, $mdSidenav, $timeout, $localSt ...

Prevent scrolling while popup is open

I found a helpful tutorial online for creating a jQuery popup (). However, due to my limited understanding of jQuery, I'm having trouble getting it to meet my needs. The issues I'm facing are: I need to prevent the webpage from scrolling when ...

Pressing the up arrow in Javascript to retrieve the most recent inputs

Is there a way to retrieve the most recent inputs I entered in a specific order? For example: I have an array with 20 elements, and every time I enter something, I remove the first element from the array and add the new input at the end. So, when I press ...

Utilize a Sails.js Single Page Application (SPA) to route all unutilized paths to a centralized controller function

I'm currently working on a project where I am building a single page application (SPA) with Sails.js as the backend. My goal is to have all routes redirect to a single controller action. However, the issue I am facing is that when I try the following ...

The formatting of the list is not being correctly displayed in the Ajax Jquery list

Trying to dynamically generate an unordered list from XML onto a jQuery mobile page has been a bit of a challenge for me. While I can display the items on the page, the styling never seems to work properly, only showing up as plain text with blue links. Is ...

Is there a way to eliminate the feature that rearranges characters in reverse order?

Is there a way to modify this code to only replace vowels with "er" instead of reversing the order of characters? I'm hoping to remove the function that reverses the character order. If you want to take a look at the code, it's available on Past ...

Having problems getting my fixed header to work on my datatable. What could be the

Struggling to make my data table Thead sticky? I attempted using position: fixed;, top: 0; with CSS but it only worked in Firefox, not Chrome, Edge, or Opera. Here is an excerpt of my Ajax code: "stateSave": false, "orderCellsTop&quo ...

Error: null value cannot be scrolled into view - testing with react, jest, and enzyme

Utilizing react version 16.3.1, jest version 16.3.1, and enzyme version 3.3.0. Inside my React Class component, I have implemented a react ref to ensure that upon mounting the component, the browser scrolls back to the top of the page. class PageView ext ...

Navigating from an error page to the homepage with Next.JS 13: A quick and easy guide

I'm currently working on implementing a feature that allows users to easily go back to the main page from an error page within the app folder. Specifically, in my weather app project, if a user enters an incorrect city, they should have the option to ...

Is there a way to extract the key and value pair from this function?

After performing a Json object to array conversion using the following code: var ticks= {firstkey: "firstvalue", secondkey: "secondvalue", thirdkey: "thirdValue"} var arr = $.map(ticks, function(value, index) { return [[in ...

Bootstrap 4 radio buttons are not aligning properly with the padding

There seems to be an issue with the alignment of Bootstrap 4 custom radio buttons and my left padding. Here is a snippet: https://i.sstatic.net/vWTNo.png This is part of the code for displaying an item <div class="p-4"> <ul class="d-flex ...

Ajax request terminates once PHP has looped for a specific duration of time (2 minutes)

My challenge involves a button that is responsible for checking over 300 posts for a specific value and other conditions using about 20 if-else statements. Strangely, the ajax call initiated by this button halts after completing around 73 loops within a sp ...

Tips for creating the ultimate footer section on your webpage

I'm trying to position the footer div (id="Footer") 10px from the bottom of the screen. Regardless of whether the page content fills the entire height of the screen or creates a scroll area, I want the div to always be at the very bottom with a 10px m ...

The Ajax page does not respond to click events when the function is declared within $(function(){ }) block

Create two functions as shown below: <script> $(function () { function myFunctionB() { alert("ddd"); } }) function myFunctionA() { alert("ddd"); } </sc ...

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

Is it possible to retrieve JSON data from the server without having to reload the page?

My approach to minimize server requests involves sending a JSON file to the client and working with that data instead. However, a challenge I'm facing is preventing the page from refreshing when receiving the JSON file. I want the data to be received ...

Next.JS CSS modules are experiencing issues with functionality

Organizing the CSS structure for a project by creating a module of CSS for each component or page can sometimes present challenges. Take a look at the code snippet below: .navbar { display: flex; justify-content: flex-start; align-items: center; pa ...

What is the best way to make a text scroll smoothly from left to right on my website?

I am currently working on my upcoming website and I could use some guidance in this area. My goal is to create a seamless horizontal scrolling effect on the page at a readable speed, but I'm having difficulty achieving this. *, *::after, *::before ...

How to customize the text color of the notchedOutline span in Material UI

I'm currently working on customizing the textfield in materialUI. This is what I am trying to modify. I am facing challenges in changing the color of the span tag that contains the text, and also in maintaining the border color when the textfield is ...

React hook form submit not being triggered

import React, { useState } from "react"; import FileBase64 from "react-file-base64"; import { useDispatch } from "react-redux"; import { makeStyles } from "@material-ui/core/styles"; import { TextField, Select, Input ...