Reputation: 17
I need to alternate the color of three numbers that contains the class '.holiday' and they are 24, 25 and 31. But with this code I get the image. After the second click, the 24 and 31 change to red and 25 turn to blue.
let holidayClick = () => {
const holidayBtn = document.querySelector('#btn-holiday');
const holidayLi = document.querySelectorAll('.holiday');
let isColored = false;
for (let li of holidayLi) {
holidayBtn.addEventListener('click', () => {
if (isColored) {
li.style.color = 'red';
isColored = false;
} else {
li.style.color = 'blue';
isColored = true;
}
});
}
};
holidayClick();
Upvotes: 0
Views: 48
Reputation: 122906
It's not exactly clear what you want to accomplish. But if you want to switch colors on certain li
-elements, using some state (isColored
), you can save the state in a data-attribute on a li
-element. The event handler for the button has to be created once, in the snippet it is created at the document level (event delegation)
document.addEventListener("click", holidayClick)
function holidayClick(evt) {
// return if the click did not originate from the button
if (evt.target.id !== "btn-holiday") { return; }
// find all li /w attribute [data-holidaycolored] and
// colorize them according to the value of the attribute
document.querySelectorAll('[data-holidaycolored]').forEach(
li => {
const isColored = !!+li.dataset.holidaycolored;
// ^ convert to number
// ^ convert number to boolean
li.style.color = !isColored ? "blue" : "red";
li.dataset.holidaycolored = +!isColored;
// ^ flip boolean and convert to number
});
}
<ul>
<li>...</li>
<li data-holidaycolored="0">21</li>
<li data-holidaycolored="0">22</li>
<li>23</li>
<li>24</li>
<li>...</li>
<li data-holidaycolored="0">31</li>
</ul>
<button id="btn-holiday">holidays</button>
It may also be that you want to colorize individual li
-elements. In that case:
document.addEventListener("click", holidayClick)
function holidayClick(evt) {
const origin = evt.target;
// return if the click did not originate from the button
if (!origin.dataset.colorholiday) { return; }
// colorize the clicked element according to the value of the attribute
const isColored = !!+origin.dataset.holidaycolored;
origin.style.color = !isColored ? "blue" : "red";
origin.dataset.holidaycolored = +!isColored;
}
li {
cursor: pointer;
}
<ul>
<li>...</li>
<li data-colorholiday="0">21</li>
<li data-colorholiday="0">22</li>
<li data-colorholiday="0">23</li>
<li data-colorholiday="0">24</li>
<li>...</li>
<li data-colorholiday="0">31</li>
</ul>
Upvotes: 1