Trying not set the background color every time the count is 7 or less, if its already red it shouldnt set it again.
<div class="parent">
<ul class="list">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
<li class="item">Item 4</li>
<li class="item">Item 5</li>
<li class="item">Item 6</li>
<li class="item">Item 7</li>
</ul>
</div>
How can I stop setting the color over and over once the count is less than 7?
var parent = document.querySelector('.parent');
parent.addEventListener('click', changeColor, false);
function changeColor( e ) {
var element = e.target;
var item = document.querySelectorAll('.item');
element.parentNode.removeChild(element);
if( item.length <= 7 ) {
parent.style.background = "red";
console.log(
item.length + " set backgroud color"
)
}
}
If I understand your question correctly, this should do the trick:
var parent = document.querySelector('.parent');
var background = 'false';
parent.addEventListener('click', changeColor, false);
function changeColor( e ) {
var element = e.target;
var item = document.querySelectorAll('.item');
element.parentNode.removeChild(element);
if( item.length <= 7 && parent.style.background != 'red') {
parent.style.background = "red";
console.log(
item.length + " set backgroud color"
)
}
You could remove event listener if count is under 7. That way, not only you're not changing color again, you're not running anything on click anymore.
if( item.length <= 7 ) {
parent.style.background = "red";
parent.removeEventListener('click', changeColor, false);
}
And if somewhere you have a function adding element, simply start listening again.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.