Nabucco
Nabucco

Reputation: 41

How to change a CSS checkbox label icon when checked WITHOUT JAVASCRIPT

I have a hamburger menu with no javascript (I can't use it, that's the assignment) using a label icon from FontAwesome and I want the icon to change to another one when the checkbox is checked, I just have no idea how to do that. I've checked online and apparently it's not possible without JS but I rather ask just in case.

The icon is directly inside the label using class and I know i can add as many labels as I want and they're just gonna stack up, but I don't know how to hide/show one of them depending on the status of the checkbox or if there's another way:

<div id="hamburger">
    <img src="thelogo.png" alt="logo">
    <input type="checkbox" id="button">
    <label for="button" class="fas fa-bars"></label>
    <ul class="items">
        <li>EPISODES</li>
        <li>INTERVIEWS</li> 
        <li>ABOUT US</li>
    </ul>
</div>

Upvotes: 2

Views: 34156

Answers (4)

If you are using React you can simply do this:

        <span>
          <Input type="checkbox" id="button" checked={isChecked} onChange={handleChange}/>
          {isChecked ? <FontAwesomeIcon icon={faCheckSquare} /> : <FontAwesomeIcon icon={faSquare} /> }
          {value}
        </span>

Upvotes: 1

Mark
Mark

Reputation: 2071

You could use multiple icons and show/hide whichever you want.

<input type="checkbox" id="button">
<label for="button" class="fas fa-bars"></label>
<label for="button" class="fas arrow-circle-up"></label>

#button:checked ~ .fa-bars {
   display: none;
}

#button:checked ~ .arrow-circle-up {
   display: inline-block;
}

Or a more elegant way would be to update the content of the icon code.

#button ~ label::before {
  content: '\f0c9'; // bars code
}

#button:checked ~ label::before {
  content: '\f0aa'; // arrow up code
}

Heres a cheatsheet of all the icon codes

Upvotes: 4

Colin Bacon
Colin Bacon

Reputation: 15619

To change the label icon when the checkbox is checked, use :before pseudo element.

Example

JsFiddle

html

<input type="checkbox" id="button">
<label for="button" class="fas"></label>

css

#button {
  display: none;
}

#button + label:before {
  content: "\f0c9"; 
}

#button:checked + label:before {
  content: "\f0aa"; 
}

Upvotes: 5

Bdloul
Bdloul

Reputation: 902

Use the pseudo class :checked : https://css-tricks.com/almanac/selectors/c/checked/

Example :

#button:checked + label {
   background : red;
}

#button:checked + label {
   background : blue;
}

That will change the background of your label when the checkbox is checked or not

Upvotes: 1

Related Questions