Steps for configuring a switch to display a color at random

Looking for a way to modify colors of a basic switch

<body>
<label class="toggle">
<input type="checkbox">
<span class="slider"></span>
</label>
</body>

    .toggle {
  --width: 80px;
  --height: calc(var(--width) / 3);

  position: relative;
  display: inline-block;
  width: var(--width);
  height: var(--height);
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
  border-radius: var(--height);
  cursor: pointer;
 }

.toggle input {
  display: none;
 }

.toggle .slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: var(--height);
  background-color: #ccc;
  transition: all 0.4s ease-in-out;
 }

.toggle .slider::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: calc(var(--height));
  height: calc(var(--height));
  border-radius: calc(var(--height) / 2);
  background-color: #fff;
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
  transition: all 0.4s ease-in-out;
 }

.toggle input:checked+.slider {
  background-color: #2196F3;
 }

.toggle input:checked+.slider::before {
  transform: translateX(calc(var(--width) - var(--height)));
 }

I've been trying to figure out how to make the color change randomly every time it's clicked. Any idea or suggestion would be appreciated!

Maybe it involves altering the .enabled/disabled states or using a different programming language/library. Despite my attempts, I haven't been able to solve this yet.

Answer №1

It's not possible to achieve this effect with just HTML and CSS, but with JavaScript it can be done easily. You can listen for a click event on an element, generate a random color each time, and change the style of the element. Here is a simple example:

const checkedSlider = document.querySelector(".toggle .slider");

const randomInt = max => Math.floor(Math.random() * max);

checkbox.addEventListener("click", e => {
  if (e.target.checked) {
    const r = randomInt(256);
    const g = randomInt(256);
    const b = randomInt(256);
    checkedSlider.style.backgroundColor = `rgb(${r},${g}, ${b})`
  } else {
    checkedSlider.style.backgroundColor = "lightgray";
  }
});

Check out this JSFiddle for a live demo.

Answer №2

function changeColor() {
  document.getElementById('btn').style.backgroundColor = generateRandomColor();
}


// Random color generation function sourced from:
// http://www.paulirish.com/2009/random-hex-color-code-snippets/

function generateRandomColor() {
  return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
 .toggle {
  --width: 80px;
  --height: calc(var(--width) / 3);

  position: relative;
  display: inline-block;
  width: var(--width);
  height: var(--height);
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
  border-radius: var(--height);
  cursor: pointer;
 }

.toggle input {
  display: none;
 }

.toggle .slider {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: var(--height);
  background-color: #ccc;
  transition: all 0.4s ease-in-out;
 }

.toggle .slider::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: calc(var(--height));
  height: calc(var(--height));
  border-radius: calc(var(--height) / 2);
  background-color: #fff;
  box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
  transition: all 0.4s ease-in-out;
 }

.toggle input:checked+.slider {
  background-color: #2196F3;
 }

.toggle input:checked+.slider::before {
  transform: translateX(calc(var(--width) - var(--height)));
 }
<body>
<label class="toggle">
<input type="checkbox" >
<span class="slider" id="btn" onclick="changeColor()"></span>
</label>
</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

Encountering a 404 error while using Node.js for app.get requests with Postgres as the

Currently, I am in the process of learning Node.js by following a tutorial that guides me on building a simple API. The tutorial utilizes a sample database for demonstration purposes, but I decided to use my own Postgres DB instead. However, when trying to ...

Is there a way to execute a JavaScript file within another JavaScript file?

I'm in the process of developing a text-based game through the console, utilizing an NPM package known as "prompts" to prompt the user for input. One specific question it asks is, "What OS do you want to run?" and returns the selection as JSON data. F ...

Unable to eliminate top padding without using universal selector

Trying to remove the top padding on a webpage, but encountering some difficulty. Here's the HTML code: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="style.css"> <title&g ...

Difficulty with conflicting styles when dynamically loading components in Nuxt3

I'm facing a challenge with my Nuxt 3 application where I need to dynamically load different Header components for Mobile and Desktop devices. I have created Header.vue and MobileHeader.vue for this purpose, and want to display them based on the dev ...

What is the best way to incorporate a dropdown header in Material-UI on a React project?

I am facing an issue where only the last Menu Dropdown is rendering, but I actually need different Menus to be displayed (with the text faintly appearing behind them). I am uncertain about how to correctly pass the props/state to make this work. import Rea ...

What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciat ...

creating dynamic navigation tabs with scroll functionality

Utilizing Bootstrap Nav Tabs and Tab panes on my website has been a smooth process. However, I am encountering some difficulty in adding extra links that not only activate the Tab Panes but also scroll to them. The issue seems to be related to a specific l ...

Using Angular Ionic for a click event that is triggered by a specific class

I am utilizing Highcharts and would like to click on the legend upon loading. With the use of Angular Ionic, how can I trigger a click on the .highcharts-legend-item class within the ngOnInit() {} method? I am aiming to click on this class as soon as the ...

Transmit JSON information from one webpage and dynamically retrieve it from another page via AJAX while both pages are active

I am attempting to transfer JSON data from page1 when the submit button is clicked and then retrieve this data dynamically from page2 using AJAX in order to display it in the console. I am unsure of the correct syntax to accomplish this task. There was a s ...

Tips for utilizing a for loop within an array extracted from a jQuery element for automation

I am looking to streamline the process using a for loop for an array containing 10 image files in the parameters of initialPreview and initialPreviewConfig. My envisioned solution involves the following code snippet: for (i = 0; i < 11; i++) { "< ...

What is the best approach to retrieve a username from a SQL database using AJAX within a Flask application

I have been attempting to retrieve the username column information from SQL using ajax, but only the username of the first ID is being returned. However, I need all usernames to be fetched. Below is the model: class users(db.Model): id=db.Column(db.I ...

The initial dispatch of a React hook triggers subsequent dispatches to fire multiple times

Whenever I include more than one dispatch in useEffect(), it causes all subsequent actions to be triggered twice. Please see the example below. Below is the complete code. Feel free to remove comments in any order you prefer. PS: I am not sure how to mak ...

Retrieve information from subcategories in the Realtime Database using Firebase

Trying to access message inputs from ALL users has been a challenge. While it can be done for a specific user, the goal is to do so for all users by specifying in the code. Each UID is unique, adding complexity to the process. The Realtime Database struct ...

Move the Material UI popover to the clicked icon's position

I am looking to create a popover similar to the image linked below. When the icon is clicked, I want the popover to display with the same user interface. https://i.sstatic.net/yvKjF.png Here is the code snippet that I have been using: {showPopOver &&a ...

Using the filter() function in jQuery allows for efficient sorting and

My current area of study is in jQuery, but I'm encountering a bit of confusion with the following code: var list = mylist.filter(function(f) { return $(f) .find('.anthing') .length > 0; }); I'm particularly puzz ...

Adding additional functionalities to ng-blur within the controller: A step-by-step guide

I am seeking to enhance the functionality of ng-blur for all input and textarea fields by adding a new function. These elements already have an existing ng-blur defined in the HTML, and my goal is to incorporate a new function into this existing setup from ...

Leveraging the sibling combinator for altering the class of a sibling SVG element with the assistance of Material

I have created an SVG picture that I am trying to animate. Behind the elements I want to animate on mouse hover, I have added transparent rectangles. The hover effect works well on these elements as the cursor changes to pointer. However, when I attempt t ...

Show just a single error message if there are two validation errors present

In my AngularJS timepicker, users can choose multiple time segments for each day. The code has validation to detect duplicates and overlapping time segments. For example, entering 11:00am - 12:00am twice will trigger two error messages: 'Overlapping t ...

In Typescript, we can use a class to encapsulate another class and then return a generic result

Trying to wrap my head around the concept of generic classes, and now I need to dynamically create another class. However, I am uncertain about how to go about it. Class A {} Class B<T> { Return T } Const c = B(A); // which is T More context on w ...

Can I use JavaScript to generate an element similar to <ion-icon name="heart"></ion-icon>?

Currently, I am utilizing a website called to incorporate icons into my buttons. It is quite straightforward with HTML when introducing a new element containing the icon. All you need to do is define a button and insert this code within it: ion-icon name= ...