I'm working on a small project which is going to have a light/dark mode toggle but I'm struggling to toggle the class on the tag.
So I'm using font awesome for the icons here is my code:
HTML:
<i class="fas fa-moon" id="toggle"></i>
JS:
function classToggle() {
document.getElementById("toggle").classList.toggle('fas fa-moon');
document.getElementById("toggle").classList.toggle('fas fa-sun');
}
document.querySelector('#toggle').addEventListener('click', classToggle);
the above code gave me the error:
InvalidCharacterError: The string contains invalid characters.
for the JS I have also tried:
function classToggle() {
this.classList.toggle('fas fa-moon');
this.classList.toggle('fas fa-sun');
}
document.querySelector('#toggle').addEventListener('click', classToggle);
but this doesn't work either and gave me the error:
TypeError: undefined is not an object (evaluating 'this.classList.toggle')
I got the code above from https://codepen.io/jacknifey/pen/XWJaKZr and it worked perfectly, but as soon as I changed the class names to the font awesome ones it stoped working. Maybe it's something to do with the SVG's. If so can anyone suggest an alternative method.
Stay Safe Thanks, Jamie :)
You don't need to put fas
into classList.toggle
method.
function classToggle() {
document.getElementById("toggle").classList.toggle('fa-moon');
document.getElementById("toggle").classList.toggle('fa-sun');
}
document.querySelector('#toggle').addEventListener('click', classToggle);
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<i class="fas fa-moon" id="toggle"></i>