Adjusting the color of an HTML slider button as it moves

In my setup, I have a straightforward slider that I plan to use for controlling the movement of a stepper motor based on the slider's position. I wanted to give the website where this will be hosted a professional look, so I've spent quite some time trying to figure out how to change the button color as it moves (given that the motor controls my boiler temperature, having a visual representation of the temperature would be neat). However, I'm facing a challenge in changing the CSS value. I understand that I can use

document.getElementById("myRange")
to target the .slider CSS, but my issue lies in targeting the .slider::-webkit-slider-thumb section, since its background determines the color of the button itself. It's proven challenging for me to reference this because I'm unsure of what the double colon signifies. From my research, I gathered that :hover and other single colon class references apply when a specific condition is met (like hovering over with the mouse), while the double colon suggests that the reference may not technically exist but can be utilized for styling - referred to as a pseudo element, I believe.

I stumbled upon examples like:

document.getElementById("testDiv").pseudoStyle("before","color","purple");

And also:

document.styleSheets[0].insertRule('#elid:hover { background-color: red; }', 0);
document.styleSheets[0].cssRules[0].style.backgroundColor= 'red';

In an attempt to adapt these examples into my own project, I tried things like this:

var sliderButton = document.getElementById("myRange");
sliderButton.pseudoStyle("::-webkit-slider-thumb","background",rgb(r, 0, b)); 
//where r and b are predefined values between 0 and 255

And also:

document.styleSheets[0].addRule('.slider::-webkit-slider-thumb','background: green');

Unfortunately, none of these methods worked for me. It's likely something very obvious that I'm missing, but for the life of me, I can't seem to figure it out. All I really need is a way to modify the .slider::-webkit-slider-thumb background value within my code. Any help or ideas would be greatly appreciated.

.slider {
      -webkit-appearance: none;
      width: 100%;
      height: 15px;
      border-radius: 5px;
      background: #c6c6c6;
      outline: none;
      opacity: 0.7;
      -webkit-transition: .3s;
      transition: opacity .3s;
    }
    .slider:hover {
      opacity: 1;
      background: grey;
    }
    .slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: red;
      cursor: pointer;
    }
    .slider::-moz-range-thumb {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: #4CAF50;
      cursor: pointer;
    }
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Answer №1

If you want to implement a dynamic color change feature based on user interactions, you can follow the approach suggested by @guest271314. By setting up an event handler for either the input or change events and generating a random color, you can achieve a versatile color scheme. Additionally, you have the option to store preferred colors in an array and select a random one from the array to ensure a limited color palette.

var s = document.getElementById("myRange");

s.addEventListener("input", function(){

  // Generate random color
  
  // Hex:
  //var color = '#'+Math.floor(Math.random()*16777215).toString(16);
  
  // RGB:
  var num = Math.round("0xffffff" * Math.random());
  var r = num >> 16;
  var g = num >> 8 & 255;
  var b = num & 255;
  var color = 'rgb(' + r + ', ' + g + ', ' + b + ')';  
  
  // Loop over the CSS rules in the document's stylesheets
  for (let {cssRules} of document.styleSheets) {
  
    // Loop over the selector and styles of each rule
    for (let {selectorText, style} of cssRules) {
      // Check the selector for a match
      if (selectorText === ".slider::-webkit-slider-thumb") {
        // Update the style:
        style.backgroundColor = color;
      }
    }
  }
});
.slider {
      -webkit-appearance: none;
      width: 100%;
      height: 15px;
      border-radius: 5px;
      background: #c6c6c6;
      outline: none;
      opacity: 0.7;
      -webkit-transition: .3s;
      transition: opacity .3s;
    }
    .slider:hover {
      opacity: 1;
      background: grey;
    }
    .slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: red;
      cursor: pointer;
    }
    .slider::-moz-range-thumb {
      width: 25px;
      height: 25px;
      border-radius: 50%;
      background: #4CAF50;
      cursor: pointer;
    }
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">

Answer №2

To dynamically change the style of a CSS rule in your document, you can iterate through document.styleSheets, check each one's .cssRules for a specific .selectorText, and then update the .style properties accordingly.

for (let {cssRules} of document.styleSheets) {
  for (let {selectorText, style} of cssRules) {
    if (selectorText === ".slider::-webkit-slider-thumb") {
      style.backgroundColor = "green";
    }
  }
}
.slider {
  -webkit-appearance: none;
  width: 100%;
  height: 15px;
  border-radius: 5px;
  background: #c6c6c6;
  outline: none;
  opacity: 0.7;
  -webkit-transition: .3s;
  transition: opacity .3s;
}

.slider:hover {
  opacity: 1;
  background: grey;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: red;
  cursor: pointer;
}

.slider::-moz-range-thumb {
  width: 25px;
  height: 25px;
  border-radius: 50%;
  background: #4CAF50;
  cursor: pointer;
}
<input type="range" min="1" max="100" value="50" class="slider" id="myRange">

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

move position when clicked-javascript animation

Is there a way to create a button that changes a div's position with a 2-second transition on the first click and then returns it back on the second click? I tried implementing this code, but unfortunately, it doesn't bring the div back. va ...

What is the best way to showcase two data frames side by side in an HTML template or webpage without using frames?

Is there a way to showcase two data frames side by side in an html template? <h3> TITLE </h3> {{stat1 | safe}}. {{stat | safe}} I attempted the above solution, but unfortunately it only displays the data frames vertically stacked instead of ...

Transform your traditional sidebar into a sleek icon sidebar with Semantic UI

I am working on customizing the semantic-ui sidebar. My goal is to have it minimize to a labeled icon when the toggle button is clicked. However, I am having trouble with the animation and getting the content to be pulled when I minimize it to the labeled ...

What is the method to retrieve the ID name of an HTML tag based on its value?

Is there a way to determine the ID of an HTML tag based on its content? For example, if I have the following textboxes: I need to identify the id with the value "A2" So the expected result is id=option2 because its value is A2 <input type="text ...

Dynamically assigning column values based on object properties

I am currently utilizing the Ionic Framework along with its grid system that is reminiscent of Bootstrap. However, I believe my query leans more towards AngularJS than specific Ionic components. Here is what I have: <ion-col *ngFor="let col of row ...

Mozilla Firefox's webpage controls adapt according to the type of authentication being used

On my .NET MVC web page, I have 3 radio buttons for selecting a value on a form. However, in a specific test environment with two authentication methods (user/password or certificate), the radio buttons mysteriously change to checkboxes when the page loads ...

I'm looking to adjust the padding on the left and right sides of the v-select menu checkbox in Vuetify 3. How

While trying to reduce the left padding of the v-select menu checkbox using the F12 debugger, I encountered an issue where the menu suddenly disappears when clicked. This makes it difficult to see the active menu. Attached is a screenshot of the select me ...

I need help figuring out how to retrieve the full path of an uploaded file in JavaScript. Currently, it only returns "c:fakepath" but I need

Is there a way to obtain the complete file path of an uploaded file in javascript? Currently, it only shows c:\fakepath. The file path is being directly sent to the controller through jquery, and I need the full path for my servlet. Are there any alte ...

Steps for updating the property "project_id" within a nested JSON array to "project_name"

Issue: [ { "project_id": 1, "project_name": "CDP", "role": "PL" }, { "project_id": 2, "project_name": "Admincer", "role": "PM" }, I am trying to extract the "project_id" property from the above JSON array and add it to another array using a specific ...

creating reactive images with Vue

The original code utilized an image in a menu as shown below: <img :alt="$t('more')" class="mobile-plus-content visible-xs" src="../../../assets/img/plus79.png" /> This results in: src="data:image/png;base64,the image" I made a mo ...

Difficulty with replacing colors in an image on certain devices when using HTML5 Canvas

I have created a 2d RTS HTML5 / Javascript game that utilizes images to represent the player's units and buildings. To achieve different variations of these images with different colors, I use a script that replaces certain colors in the original imag ...

Implementing Pagination or Infinite Scroll to Instagram Feed

Currently, I am working on creating an Instagram feed for a fashion campaign where users can hashtag their photos with a specific tag. Using the Instagram API, the script will pull all recent posts with this common tag to display on the webpage. Instagram ...

Guide to easily printing a page in Angular 4 using TypeScript

When using my web app, there are certain pages where I need to print only a specific component without including the sidebar. I have written the following TypeScript code to achieve this: print() { window.print(); } The relevant HTML code begins with: & ...

Changing the cursor to a waiting state following a mouse click

Looking for some help here - when I click a button, the cursor remains standard and doesn't show loading. Any suggestions on how to fix this? Below is the snippet of my code: <div class="signup"> <input type="submit" value="Sign Up" tit ...

The content div in CSS is causing the menu div to be displaced

I have encountered a difficulty in describing the issue at hand as I am still in the learning phase and consider myself a beginner. Within my container div, there are two other divs - one for the menu and another for the content. Both of these divs float ...

Running a series of functions consecutively with JQUERY

Currently, I am facing an issue with using an ajax method .load to replace the content of a div. The library I am working with does not allow me to replace the content of a div as some functions continue to run in the background. To overcome this challeng ...

Multiplying array elements within the Vuex state with the assistance of Socket.io

I have developed an application using Vue and Vuex that connects to a Node/Express backend with Socket.IO to instantly push data from the server to the client when necessary. The data sent to the clients is in the form of objects, which are then stored in ...

Struggling to get .parent().toggleClass to function properly

Check out this fiddle: https://jsfiddle.net/qxnk05ua/2/ I'm trying to get the background color to change when I click the button, but it's not working. Can you help me figure out why? This is the Javascript code I'm using: $(document).rea ...

Slide the next section over the current section using full-page JavaScript

I'm currently developing a website utilizing the FullPage.JS script found at this link . My goal is to have the next section slide over the previous one, similar to what is demonstrated in this example. I've attempted setting the position to fix ...

The inner nested ng-repeat section is not properly binding to the scope variable and appears to be commented out

In my code, there is a nested ng-repeat set up. The 'boards' variable in the scope is an array that contains another array called 'tasks', which also consists of arrays. In the innermost ng-repeat, I am attempting to bind to task.conten ...