How to disable scroll to change number in field using JavaScript

When a number is entered in a container and clicked on a button the scroller option to change the number is disabled to fixe the entered value.

Given an HTML document containing <input type = “number”> attribute and the task is to disable the mouse scroll wheel to change number value using JavaScript/jQuery.

Approach:

  • Select the element.
  • Add an event to that element which will call a function when scrolling starts.
  • Make the element blur on scrolling.
<!DOCTYPE HTML>
<html>

<head>
	<title>
		How to disable scroll to change number
		value in <input type="number">
		attribute in JavaScript/jQuery?
	</title>
	
	<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
	</script>
</head>

<body style = "text-align:center;">
	
	<h1 style = "color:green;" >
		GeeksForGeeks
	</h1>
	
	<p id = "GFG_UP" style =
		"font-size: 15px; font-weight: bold;">
	</p>
	
	<form>
		<input id = "input" type = "number" />
	</form>
	
	<br>
	
	<button onclick = "GFG_FUN()">
		click here
	</button>
	
	<p id = "GFG_DOWN" style =
		"font-size: 24px; font-weight: bold; color: green;">
	</p>
	
	<script>
		var el_up = document.getElementById("GFG_UP");
		var el_down = document.getElementById("GFG_DOWN");
		
		el_up.innerHTML = "Click on the button to disable"
					+ " scrolling on input element.";
		
		function GFG_FUN() {
			var input = document.getElementById("input");
			
			input.addEventListener("mousewheel",
				function(event){
					this.blur()
				});
			
			el_down.innerHTML = "Mouse wheel disabled!";
		}
	</script>
</body>

</html>

Leave a comment

Your email address will not be published. Required fields are marked *