PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] What is a Proper way to use Input range listener

 October 15, 2022     dom, dom-events, input, javascript, loops     No comments   

Issue

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...


Solution

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.)



Answered By - Luke Persola
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing