JSmith
JSmith

Reputation: 4808

How can I trigger a function while number is changing in an input of type number?

Let's say I have an input of type number as so:

<input type="number" step="0.05">

I would like to trigger a canvas rendering function called for example renderCanvas() each time the number is stepping up or down.

This solution:

<input type="number" step="0.05" onchange="renderCanvas()">

works when I use keyboard to decrement/increment my value, but when I use the arrows and the mouse the function only triggers when the mouse is up.

function renderCanvas()
{
  console.log("the value is " + document.getElementsByTagName("input")[0].value)
}
<input type="number" step="0.05" onchange="renderCanvas()">

How can I achieve the same result as when the keyboard is used with using the mouse?

ps: the question is not the same as this post as the function only triggers when key/mouse is up. What I would like is my function triggering every time the value changes on screen.

Upvotes: 0

Views: 1131

Answers (2)

JSmith
JSmith

Reputation: 4808

The answer is to use the input event.

Upvotes: 0

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

You should use keyup and mouseup events since you have added the tag for jquery if I understood correctly you want the alert/console.log to appear or show the value whenever you change the value using the mouse or the keyboard, if that is correct here is the demo you can see the console prints the value every time you use mouse, keypad, num keys, or arrow keys. Hope it helps

var here = 0;
$("#my-input").on('keyup mouseup change', function() {
  if ($(this).val() !== '') {
    console.log(here++);
    console.log("the value is " + $(this).val());
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="my-input" type="number" step="1">

EDIT

Or if you are looking to detect the number change if you keep your key pressed on the arrow of the number input that appears when we hover over it then i dont think it would be an easy task to do, in that case you should use a custom slider and bind the slider to a hidden input to keep updating the value and bind the onchange to that hidden input which keeps on updating you cavas

Upvotes: 1

Related Questions