marchelee
marchelee

Reputation: 11

How do you change Material Icon permanently using CSS and HTML?

I am trying to change the icon permanently from "add" to "done" after I click the icon. If I click the icon again, it should change from "done" to "add." I am wondering if it is possible to do this with CSS without using Javascript.

.material-icons::before {
  content: "add";
}

section:active .material-icons::before {
  /*background-color: red;*/
  content: "done";
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons|Open+Sans" rel="stylesheet">

<section>
  <span id="btn1" class="material-icons"></span>
</section>

Upvotes: 1

Views: 2059

Answers (2)

James Douglas
James Douglas

Reputation: 3446

The way this works, is there are two <span>'s, (one with the add and one with the done icon) and a checkbox all stacked on top of each other, an the done icon is hidden. The add icon is pointer-events: none;, and when you click on it the checkbox gets checked. Then the add icon gets hidden, and the done icon gets shown.

(Only works if you click directly on the text)

.done,
.add, .done {
  position: absolute;
  top: 0;
  left: 0;
  background-color: white;
}
.done { display: none; }
.add { display: inline-block; pointer-events: none; }
label {
  
  display: inline-block;
  cursor: pointer;
  position: relative;
}
input[type=checkbox] { position: absolute; top: 0; left: 0; }
input[type=checkbox]:checked~.done { display: inline-block; }
<link href="https://fonts.googleapis.com/icon?family=Material+Icons|Open+Sans" rel="stylesheet">

<input type="checkbox">
<div class="add">
  <span id="btn1" class="material-icons first">add</span>
</div>
<div class="done">
  <span id="btn1" class="material-icons">done</span>
</div>

Upvotes: 0

Bal&#225;zs Varga
Bal&#225;zs Varga

Reputation: 1856

Here's the simplest CSS checkbox hack solution, you can start from here:

/* The hack */
input[type=checkbox] {
   display:none;
}
label {
  -webkit-appearance: push-button;
  -moz-appearance: button; 
  display: inline-block;
  cursor: pointer;
}

/* Default State */
input[type=checkbox] + section .material-icons::before {
   content:"add";
}

/* Toggled State */
input[type=checkbox]:checked + section .material-icons::before {
   content:"done";
}
<link href="https://fonts.googleapis.com/icon?family=Material+Icons|Open+Sans"
  rel="stylesheet">

<label>Click Me
<input type="checkbox">
<section>
  <span id="btn1" class="material-icons"></span>
</section>
</label>

Upvotes: 2

Related Questions