How can I use javascript to toggle a class?
I attempted to colorize clicked-on text by giving the element a class, and that works (the text turns red).
But when I click on the same element twice, the class is not removed. I used toggle class for this but it doesn't seem to work.
const txts = document.querySelectorAll('.txt');
const txtColor = (txt) => {
txt.addEventListener('click', e => {
if (e.target.classList.contains('txt')) {
txts.forEach(txt => txt.classList.remove('red'));
e.target.classList.toggle('red');
}
});
}
txtColor(document.querySelector('ul'));
<ul>
<li class="txt">Lorem ipsum dolor.</li>
<li class="txt">Lorem ipsum dolor.</li>
<li class="txt">Lorem ipsum dolor.</li>
</ul>
You don't really need the textColor() function, so let's remove that. Then, it might be easier to compose your logic if you move the toggle function into its own function.
One place to be careful is when you are toggling the classes. In your original code, you cannot toggle the same LI off / on / off / on.
Here's why:
First, the code removes the red class from all the LIs (a good strategy) - but then, toggle is used to toggle the clicked LI's class.
Think about that... If the LI is already red, then you remove the class from all LIs (now none of them are red), then you toggle the LI that was already red, it will turn red again - and it looks like nothing happened. But it went red -> nothing -> red very, very fast. Too fast to see it happen.
Therefore, you can first check if the LI already has the red class, and only toggle it if it didn't already have that class.
This structure might help you to see it better.
const txts = document.querySelectorAll('.txt');
txts.forEach((txt) => {
txt.addEventListener('click', (e) => toggleColor(e));
});
function toggleColor(e){
const doRed = e.target.classList.contains('red');
txts.forEach(txt => txt.classList.remove('red'));
if (!doRed) e.target.classList.toggle('red');
}
.red{
color: red;
}
li{
user-select: none;
}
<ul>
<li class="txt">Lorem ipsum dolor.</li>
<li class="txt">Lorem ipsum dolor.</li>
<li class="txt">Lorem ipsum dolor.</li>
</ul>