I have a class name called (bi bi-clipboard), I want to when I click on it to change the class name to (bi-clipboard-check), so the problem is that it added the class name next to the other class name like this:
before clicking:
<i class="bi bi-clipboard" onclick="changeIcon(this)"></i>
After clicking:
<i class="bi bi-clipboard bi-clipboard-check" onclick="changeIcon(this)"></i>
Method:
function changeIcon(icon){
icon.classList.toggle("bi-clipboard-check");
}
I saw somewhere else that was using fontawesome when you click on it, the class toggles by toggle() javascript method, and it works, but mine doesn't work as two class-names are next to each other. any solutions will be appreciated.
if you can use jQuery, you can toggle the classes separately - see JQUERY demo below
$(function() {
$(".bi").on('click', function() {
$(this).toggleClass("bi-clipboard-check");
$(this).toggleClass("bi-clipboard");
console.log($(this).prop('classList').value);
});
});
.bi {
height: 100px;
width: 100px;
display: inline-block;
background-color: green;
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<i class="bi bi-clipboard"></i>
OR, you can just toggle the two classes separately.
See plain JS demo below
function changeIcon(thisEl) {
thisEl.classList.toggle("bi-clipboard-check");
thisEl.classList.toggle("bi-clipboard");
console.log(thisEl.classList.value);
}
.bi {
height: 100px;
width: 100px;
display: inline-block;
background-color: green;
border: 1px solid red;
}
<i class="bi bi-clipboard" onclick="changeIcon(this)"></i>
If you don't want to use jQuery,
using contains() method
you can check if classlist contains bi-clipboard and replace it with bi-clipboard-check and vice versa
function changeIcon(icon) {
if (icon.classList.contains("bi-clipboard")) {
icon.classList.replace("bi-clipboard", "bi-clipboard-check");
}
else if (icon.classList.contains("bi-clipboard-check")) {
icon.classList.replace("bi-clipboard-check", "bi-clipboard");
}
}
using toggle() method
function changeIcon(icon) {
icon.classList.toggle("bi-clipboard-check");
icon.classList.toggle("bi-clipboard");
}