Updating the color of tick marks on checkboxes

I have successfully updated the background color of my checkboxes using a custom function. However, the tick mark on the checkbox now turns black instead of remaining white. How can I keep the tick mark white while changing the background color?

Here is the HTML code snippet:

<div v-for="category in categories" :key="category.id">
     <div>
        <input type="checkbox" class="categoryInput" @change="input()" 
        :true-value="category.id" false-value="0" v-model="currentCategory"/>
        <label class="form-label">{{category.name}}</label>
      </div>
</div>

And here is the JavaScript function being used:

input(){
        var color = JSON.parse(localStorage.getItem('coloring') || '[]').CTAButtons
        let collection = document.getElementsByClassName("categoryInput");
        for (let i = 0; i < collection.length; i++) {
            collection[i].style.accentColor = color
        }
    }

The background color changes successfully after running the function, but unfortunately, the tick mark on the checkboxes also changes to black. You can view the output here.

Answer №1

The default tickmark color of an HTML checkbox is determined by the browser and cannot be altered. However, you have the option to create your own customized checkbox and customize its appearance according to your preferences.

Below is an example of how you can create a custom checkbox using HTML and CSS:

<label class="container">
    <input type="checkbox" checked="checked" />
    <span class="checkmark"></span>
</label>

To style the custom checkbox, you can use the following CSS:

.container {
  display: block;
  position: relative;
  padding-left: 35px;
  margin-bottom: 12px;
  cursor: pointer;
  font-size: 22px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Hide the default browser checkbox */
.container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

/* Customize the look of the checkbox */
.checkmark {
  position: absolute;
  top: 0;
  left: 0;
  height: 25px;
  width: 25px;
  background-color: #eee;
}

/* Add styling on hover */
.container:hover input ~ .checkmark {
  background-color: #ccc;
}

/* Style the checkbox when it is checked */
.container input:checked ~ .checkmark {
  background-color: #3bb0a8;
}

/* Create the checkmark */
.checkmark:after {
  content: '';
  position: absolute;
  display: none;
}

/* Display the checkmark when checked */
.container input:checked ~ .checkmark:after {
  display: block;
}

/* Style the checkmark icon */
.container .checkmark:after {
  left: 9px;
  top: 5px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 3px 3px 0;
  -webkit-transform: rotate(45deg);
  -ms-transform: rotate(45deg);
  transform: rotate(45deg);
}

For a live demo of this custom checkbox implementation, you can visit this JSFiddle link.

Answer №2

One of the main benefits of using Vue is its ability to create custom components. Here is an example of how you can implement this:

Check it out in action on StackBlitz

You may need to adjust the code to fit your specific needs.

<template>
  <div v-for="category in categories" :key="category.id">
    <div>
      <label class="form-label categoryInput">
        <span class="material-icons icon" v-if="isChecked(category.id)">check_box</span>
        <span class="material-icons-outlined icon" v-if="!isChecked(category.id)">check_box_outline_blank</span>
        <input type="checkbox" @change="input()" :value="category.id" v-model="currentCategory"/>
        {{ category.name }}
      </label>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Checkbox',
  data: function () {
    return {
      currentCategory: [],
      categories: [
        { id: 1, name: 'alpha' },
        { id: 2, name: 'beta' },
      ],
    };
  },
  props: {},
  methods: {
    isChecked(categoryId) {
      return this.currentCategory.indexOf(categoryId) !== -1;
    },
    input() {
      var color = '#3bb0a8';
      let collection = document.getElementsByClassName('categoryInput');
      for (let i = 0; i < collection.length; i++) {
        const icons = collection[i].querySelectorAll('.icon');
        icons.forEach((iconEle) => {
          iconEle.style.color = color;
        });
      }
    },
  },
};
</script>

<style scoped>
label.categoryInput {
  display: flex;
  justify-content: center;
  align-items: center;
}
label.categoryInput input[type='checkbox'] {
  width: 0;
  height: 0;
}
</style>

Important

Add the following to the header of your index.html file:

<link href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Two+Tone|Material+Icons+Round|Material+Icons+Sharp" rel="stylesheet">

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

Sharing CSS styles among multiple single-page applications (SPAs) developed using the React

I am currently working on multiple micro SPAs that exist independently within an Express environment. I am facing a challenge with importing a global CSS file that is located outside of the apps, as it is not being recognized. The use of @import url(asset ...

intervals should not be attached after being cleared by a condition

I am facing an issue with my slider that has a play button to change the slide image and a pause button. When I click on play, it functions as intended. However, when I pause and try to play again, it does not work. Although I clear the interval using th ...

Vue is currently running in development mode. Please note that both $attrs and $listeners are set as readonly variables

Encountering an unusual issue with Vue 2, I have faced this problem a couple of times before and resolved it by identifying the culprit that was importing another instance/version of Vue to eliminate the $attrs/$listeners warnings. Recently, I decided to ...

Can an AJAX request continue running even after the user has moved to a different page within the website?

Currently on my website, users are able to submit a form using ajax. The response, indicating whether the form was successfully submitted or if there was an issue, is displayed in an alert message. However, due to the asynchronous nature of this process, i ...

Prevent using href for opening the browser when clicked

In the control, there is an href link that triggers a javascript function and passes a variable to it: <a href="<%#XPath("link").ToString()%>" onclick="return getLink(this)">Link</a> I'm looking for a way to prevent the browser fro ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

What is the best way to send information from one screen to a flatlist in React Navigation?

Currently, I am retrieving data from an API in the form of a JSON file. My goal is to pass this data from the main app to the appStack and then to the sessionsStack before displaying it on the home page. However, my console logs indicate that the data only ...

Managing user logins across different sessions using passport.js, mysql database, and express-session

Currently, my app utilizes Passport.js for user authentication with Facebook, which is functioning properly. The issue arises when my node.js server is restarted and the users are automatically logged out. It appears that using express-sessions would be a ...

I'm only seeing output on two of my input boxes - what's going on?

Currently in the process of learning JQUERY/HTML, I decided to create a shopping cart. My goal is to display the subtotal, tax, shipping costs, and total cost in input boxes. While I successfully displayed the sub total and shipping cost, I encountered an ...

Is there a way to have my MUI Typography component display a unique image cursor when hovered over?

After some testing, I found that setting the cursor to cursor: pointer works perfectly fine. However, my goal is to use a custom image as a cursor. The image is saved in both my src and public folders, but I seem to be struggling with the syntax when using ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

Looking for a custom header logo that seamlessly blends with your image slider?

I'm just starting to learn about HTML and I'm trying to create a header with a logo overlapping on an image slider. I followed the method mentioned in this post: How would you make two <div>s overlap? Unfortunately, I'm still having t ...

display the designated image as a priority

I am designing a loading screen for my website that includes the loading of multiple images, scripts, and other elements. While the HTML and CSS part is working well, I need to ensure that the "loading..." image is loaded before anything else on the page. ...

Experiencing difficulties with utilizing height percentages for CSS divs

Despite encountering similar issues with others, I am still unable to resolve the problem on my own. Your assistance is greatly appreciated. Currently, I am developing a guestbook in PHP using an HTML template. The issue I am facing is that the div elemen ...

Are you curious about how jQuery can be used to group buttons together?

In my ASP.NET MVC application, I incorporate JQUERY to enhance the user experience. I am curious if there is a way to group buttons together, not radio buttons but regular buttons. Can I have buttonA + buttonB + buttonC grouped together with some space i ...

Over-extended Affix in Bootstrap 3.1.0

I'm currently using Bootstrap 3.1.0. The issue I've encountered is that when the "affix" becomes too long for the viewport, it ends up getting cut off and doesn't display the bottom items. Is there a way to make Bootstrap's affix featu ...

Send all state values to the child component

I have an old application that sends a JSON to generate a multi-page form. I'm working on creating a universal multi-page form component where we can simply input a JSON to produce a form. The app utilizes a function called buildFormState which initi ...

Unlocking the Power of Marionette.CompositeView: Passing Parameters to Marionette.ItemView

Is there a way to access the app.vent from Marionette.ItemView? One solution might be to pass a parameter (app.vent) to Marionette.ItemView from Marionette.CompositeView. Here's the code snippet: // view/compositeView.js define([ 'marionet ...

Error message "TypeError: onClick is not a function" occurs when attempting to use a prop in a functional component

I am encountering issues while trying to utilize the onclick function as props. It shows an error message 'TypeError: onClick is not a function' when I click. What should I do? 7 | <Card 8 | onClick={() => onClick(dish ...

My @media queries are causing me some issues

Struggling with my @media queries. Once I upload my website on github, it fails to scale properly. However, when testing it in Webstorm (JetBrains), everything seems to be working fine. Any assistance would be greatly appreciated! Here is the link to my w ...