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

Browser refusing to acknowledge jQuery/JavaScript (bootstrap)

Here is where I include the necessary jQuery libraries and my custom jQuery code: <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script src= ...

The protractor-jasmine2-html-reporter fails to generate an HTML report

In my protractor config.js, I have set up the configuration to generate screenshots in a specific folder, but the HTML report is not being generated. I have followed the steps mentioned in this guide: https://www.npmjs.com/package/protractor-jasmine2-htm ...

Utilizing async/await in JavaScript within a class structure

I am facing a dilemma in using the new async/await keywords within the connect method of my JavaScript class. module.exports = class { constructor(url) { if(_.isEmpty(url)) { throw `'url' must be set`; } ...

The date retrieved from the MySQL database is failing to show up properly in an HTML table even after applying the date_format

I am struggling with a piece of HTML code that retrieves data from a database and displays it in an HTML table. The problem is, everything shows up except for the date field. Oddly enough, when I execute the query in the MySQL command line, the date displa ...

Make sure PTable maintains a horizontal layout on any device with PrimeNG

When I view my Ptable on desktop or iPad, it looks like this: https://i.stack.imgur.com/ONqZV.png However, when I switch to a device like an iPhone X, it changes to this layout: https://i.stack.imgur.com/H2q7j.png I want the horizontal layout to displa ...

Show the flex items arranged horizontally

This template is generated dynamically by Django: <div class="center row"> <h3><span>The Core</span></h3> {% for member in core %} <a class="core_img " href="#"> <div class="img__overlay"> ...

Double the Trouble: jQuery AJAX Making Two Calls

I've already posted a question about this, but I have now identified the exact issue. Now, I am seeking a solution for it :) Below is my code snippet: $('input[type="text"][name="appLink"]').unbind('keyup').unbind('ajax&apos ...

The ng-repeat ng-switch combination is not functioning as expected

My data can be simplified to the following in my code: function DemoCtrl($scope) { $scope.myData= [ {text: "blah", other: 3, V: 'caseOne'}, {text: "blah", other: 3, V: 'caseTwo'}, {text: "blah", other: 3, V ...

Unable to delete the margin of Material-ui TextField

Having trouble removing the padding around material-ui's TextField component when using styled-components and inline styling. Any solutions to this issue? Interestingly, the inline width property is functioning correctly, unlike the styled-component w ...

Encountering an error with the node module timestampnotes: 'command not recognized'

I am encountering an issue while trying to utilize a npm package called timestamp notes. After executing the following commands: $npm install timestampnotes $timestamp I receive the error message: timestamp:126: command not found: slk Subsequently, I ...

Guide on loading numerous JavaScript files into a database using the mongo shell

I am faced with the task of loading multiple js files that contain collections creations and seeds into my database using the mongo command. Currently, I have been manually loading data from each file one by one like so: mongo <host>:<port>/< ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Creating tiles that can be easily stacked to the side

Seeking a solution to a unique layout challenge, I am hoping for some guidance. After searching and not finding exactly what I need, I turned to this platform for help. I want to create a view where multiple boxes (divs) are contained within the same paren ...

Choose a particular character in a text that corresponds with a regular expression in Javascript

I am looking to replace the symbols < and > within the text. I have constructed a regular expression as follows: (<span[^>]+class\s*=\s*("|')subValue\2[^>]*>)[^<]*(<\/span>)|(<br(\/*)>) This ...

Issue with static resource fetching when referencing a .js file within an HTML document while using Flask

My HTML file loads my OpenLayers JavaScript file (which displays a map frame) when opened directly. However, when running the HTML from my Flask python app, the JavaScript file/object fails to load (resulting in no map display, just some heading text). I ...

A guide on implementing multiple ternary operators in a Vue.js template

Is it possible for a template to return three different values instead of just two, based on the data? I am familiar with using two conditions, but is there a way to use more than two without getting a syntax error? <option {{ change === 1 ? &apos ...

Show buttons in varying styles aligned next to each other

Here is the code snippet I'm currently working with: <fieldset class=last> <button>Refresh</button> <button> Clear</button> </fieldset> <form method="POST" action="*******"> <button> Down ...

JQuery not refreshing data values

function addToRewardDatabase() { var rewardValue = "98"; $.post("db/mkreward.php", { proid: getURLParameter("id") }, function(data) { rewardValue = "99"; alert(rewardValue); }); alert(rewardValue); return ...

The while loop is unyielding, persisting beyond the realm of

After executing this script, it displays the HP values for both Pokemon. Pressing 1 and pressing enter subtracts your attack points from the enemy's hit points. The goal is to stop the battle when either you or the enemy reaches 0 or below hit points ...

How can mongoose be used to modify user information in a database?

Hey there, I'm currently working on a personal project and came across an issue. I've successfully set up my (steam) user data to save in mongodb through mongoose. Right now, I have it set to only save a new user if they are not already in the da ...