Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CSS doesn't change background when adding class

I’m trying to build a selection menu and I want to change the background color of a button when it is clicked. I’m using this code:

<div id="sort-contain">
    <div id="sort-select">
        Selected
    </div>
</div>

CSS:

#sort-select {
  background-color: lightgray;
}

.sort-select-active {
  background-color: grey;
}

And I try to apply the sort-select-active class to my sort-select div using this JS code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var selected = false;

select.onclick = (e) => {
    selected = !selected;

    if (selected)
      select.classList.add("sort-select-active");
    else 
      select.classList.remove("sort-select-active");
};

The class is successfully added to the element, but the background color doesn’t change. Is there a conflict between the different background colors defined?

>Solution :

You set a background-color via an id, then you set an other via a class, the first one will always be applied, cause has an higher priority. Change the #sort-select id by a class, or use inline styles like so :

var selected = false;

select.onclick = (e) => {
    selected = !selected;

    if (selected)
    
      slect.style.backgroundColor ="gray"
    else 
     slect.style.backgroundColor ="lightgray"
};

or add !important word like so :

.sort-select-active {
  background-color: grey!important;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading