Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Increase and decrease number while pressing

I have two clickable spans that can increase and decrease number inside a input
by saving the opreation inside them using an id then loop on them and do the opreation using eval() , i want to increase the number and decrease it while pressing not only on click
(Long Press)

 <span id="--">-</span>
 <input class="num" type="number" max="50" value="0" min="1" disabled />
 <span id="++">+</span>
let num = document.querySelector(".num");
let controllers = document.querySelectorAll(".control span");

controllers.forEach((c) => {
  c.onclick = function (e) {
    let op = e.target.id;

    eval("num.value" + op);

  };
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You should use the mousedown event instead of click, and set some interval that does your logic at some rate of time.

Also I’m not sure why you’re using the id property and not some data property maybe, this isn’t a safe usage of this property. Also you should use event listeners instead of directly adding the function on the property.

 <span data-op="--">-</span>
 <input class="num" type="number" max="50" value="0" min="1" disabled />
 <span data-op="++">+</span>
let num = document.querySelector(".num");
let controllers = document.querySelectorAll(".control span");

controllers.forEach((c) => {
  let interval
  c.addEventListener('mousedown',function (e) { // mouse down - start ticking
    let op = e.target.getAttribute('data-op'); // get data property
    interval = setInterval(() => {
      eval("num.value" + op);
    }, 100) // set interval tick time here
  });

  c.addEventListener('mouseup',function (e) { // mouse up - stop ticking
    clearInterval(interval)
  });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading