Disable scroll on input type number – Javascript
Ever come across a problem where you enter some value in input type number and while you scroll down or up, you will see that the value of that input field is changed. It is because of the default behavior of the browser, it increments or decrements the value of input fields having “type” attribute valued as “number” as long as the user is scrolling inside that input field. So, let’s learn how to disable scroll on input type number for these situations.
However, there are multiple ways to prevent this behavior. But the simplest solution we came across is by removing the focus from that input field as long as the user is scrolling inside that input field. We are calling it “simplest” because it does not even need jQuery.
yes NO JQUERY !!!
Just paste the following code at the end of the file where you want to disable this scrolling behavior:
var inputTypeNumbers = document.querySelectorAll("input[type=number]");
for (var a = 0; a < inputTypeNumbers.length; a++) {
inputTypeNumbers[a].onwheel = function (event) {
event.target.blur();
};
}
Explanation
querySelectorAll will return all the nodes that matches the selector passed in as an argument. We are selecting all input fields which have a field attribute having value as “number”. This will return an array which we can use to loop through all nodes.
Next, we are looping through all input type numbers and inside this loop. We can perform a specific action on each node. We are overriding onwheel event, which is called whenever we move the mouse wheel inside the input field. In this event, we are receiving a variable from parameter named as “event”. It contains all the functions and attributes of this event.
We have an object named “target” in this event object which holds the actual input field node. Although we can use the “inputTypeNumbers[a]” inside the function event, it is better to use the event.target object. All input fields in HTML5 have a function named “blur()” which removes the focus from that input field. Calling this function will remove the focus from that input field and thus the scrolling of numbers will not occur.
That’s how you can disable scroll on input type number using Javascript’s “onwheel” event.