Dimi Ansari
Dimi Ansari

Reputation: 404

classlist.toggle not working for fa-check

I have written the following code for toggling a dash with a check, the desired toggling is not happening:

function myFunction(x) {
  x.classList.toggle("fa-check");
}
.fa {
  font-size: 50px;
  cursor: pointer;
  user-select: none;
}

.fa:hover {
  color: darkblue;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<i onclick="myFunction(this)" class="fa fa-minus"></i>

Also surprisingly, if I replace fa-minus with fa-check and vice-versa, the code seems to work!

Could anybody suggest a solution to this? As I need the first method to be working.

Upvotes: 1

Views: 2328

Answers (3)

Temani Afif
Temani Afif

Reputation: 273031

You need to toggle the fa-minus at the same time also. As actually you are having both of them when you add the fa-check so one is overidding the other.

You can also rely on Font Awesome classes to increase size:

function myFunction(x) {
  x.classList.toggle("fa-check");
  x.classList.toggle("fa-minus");
}
.fa {
  cursor: pointer;
  user-select: none;
}

.fa:hover {
  color: darkblue;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<i onclick="myFunction(this)" class="fa fa-5x fa-minus"></i>

Upvotes: 1

connexo
connexo

Reputation: 56753

Do not use inline event handlers like onclick, instead attach an event listener programmatically. Also you need to toggle .fa-minus as well, otherwise you get an element that looks like

<i class="fa fa-minus fa-check"></i>

in which case whatever class is defined later in FA's css wins.

document.querySelector('.fa.fa-minus').addEventListener('click', function(e) {
  e.target.classList.toggle("fa-check");
  e.target.classList.toggle("fa-minus");
})
@import "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css";

.fa {
  font-size: 50px;
  cursor: pointer;
  user-select: none;
}

.fa:hover {
  color: darkblue;
}
<i class="fa fa-minus"></i>

Upvotes: 0

yajiv
yajiv

Reputation: 2941

Actually, it is working but fa-check is append to the already exist classList so when you add fa-check classList become fa fa-minus fa-check and fa-minus take the priority show you can not able see effect of fa-check. Just toggle fa-minus as well and you will see output. Try below.

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <style>
.fa {
font-size: 50px;
cursor: pointer;
user-select: none;
}

.fa:hover {
color: darkblue;
}
</style>
</head>
<body>

<i onclick="myFunction(this)" class="fa fa-minus"></i>

<script>
function myFunction(x) {
    x.classList.toggle("fa-check");
    x.classList.toggle("fa-minus");
}
</script>

</body>
</html>

Upvotes: 0

Related Questions