let say I have a code:
for (let i = 0; i < rangeValue * rangeValue; i ) {
const getDivs = document.createElement('div');
getDivs.setAttribute('class', 'screen-divs');
screen.appendChild(getDivs);
screen.style.gridTemplateColumns = `repeat(${rangeValue}, auto)`;
screen.style.gridTemplateRows = `repeat(${rangeValue}, auto)`;
}
which is work fine, it display the exact div
amount I want, but when I want to use it on Input Range Listener, as we all know it will increment the whole time Input changed, no matter Input goes up or down, it will always gone up. Now I want it to be work as I expect: that when I slide it up it must be go up, and when I slide it down it must be go down.
here's the function listener:
range.addEventListener('input', (e) => {
const rangeValue = e.target.value;
for (let i = 0; i < rangeValue * rangeValue; i ) {
const getDivs = document.createElement('div');
getDivs.setAttribute('class', 'screen-divs');
screen.appendChild(getDivs);
screen.style.gridTemplateColumns = `repeat(${rangeValue}, auto)`;
screen.style.gridTemplateRows = `repeat(${rangeValue}, auto)`;
}
})
I am going to confuse how to handle this input
event. please help.
actually the loop
is rendring 64 x 64 divs maximum, which is around 4096. and input
event has infinity...
CodePudding user response:
Your code adds divs but never removes them, so the number always increases. To keep the number in sync with the input, every time your code runs it should change the number of divs to the number in the input. For example, you could first remove all the divs using removeAllChildNodes
, then add the correct number the same way you do now. But since you add so many, it would be a good for performance to add them all at once, so you might want to use innerHtml
.
(Also, you should just set styles one time after the input changes instead of in every iteration.)