Html input no scroll

Disable scroll in input field

I’ve got an input field with a background image to separate the letters in boxes. The problem appear when I reach the end of the input: the input view scrolls down due to the cursor position placed after the last letter. The problem How can I avoid the view to scroll in my inputs? I’ve tried to add an » overflow:hidden » and to set a » maxlength «, the problem is still there. edit: a simple demonstration (My goal is to avoid the «move effect» when the 4th letter is entered)

Share you working/attempted code.! Let us what have done so far. this is not a proper way to ask question on Stackoverflow.

You could just make the input slightly wider so that there’s space for the carat after the fourth character: jsfiddle.net/n23dfs4t/1

2 Answers 2

CSS solution

Like said in comment, you could slightly increase the with of your input to prevent this ‘jump’ behavior like : width : 202px

JavaScript solution

If you can’t/ don’t want to change the width of your input you can prevent the keypress event, then check the length of the input value. If it less than 4 add it else do nothing.

Jquery way:

var t = $('#input-form'); t.keypress( function(event) < //Prevent the value to be added event.preventDefault(); //Regex that you can change for whatever you allow in the input (here any word character -->alphanumeric & underscore) var reg = /\w/g; //retreive the key pressed var inputChar = String.fromCharCode(event.which); //retreive the input's value length var inputLength = t.val().length; if ( reg.test(inputChar) && (inputLength < 4) ) < //if input length < 4, add the value t.val(t.val() + inputChar); >else < //else do nothing return; >>); 

Pure JavaScript:

var t = document.getElementById('input-form'); t.addEventListener('keypress', function(event) < //Prevent the value to be added event.preventDefault(); //Regex that you can change for whatever you allow in the input (here any word character -->alphanumeric & underscore) var reg = /\w/g; //retreive the input's value length var inputChar = String.fromCharCode(event.which); //retreive the input's value length var inputLength = t.value.length; if ( reg.test(inputChar) && (inputLength < 4) ) < //if input length < 4, add the value t.value = t.value + inputChar; >else < //else do nothing return; >>); 

Источник

Читайте также:  Can run java in chrome

Disable scrolling on « in React

This question was asked before but provided solution is just for jQuery , as I’m facing same problem in ReactJs. Is it possible to disable the scroll wheel changing the number in an input number field? I removed spinner arrows using CSS but mouse wheel still working and messing the functionality. I want input type number because it gives numeric keyboard on mobile/touch devices.

yes I’ve tried, even I tried to write code in public/index.html to remove mousewheel event in javascript (outside of react), but it didn’t work. may be I did some mistake

I have tried this — this.getWheel(e)>> and inside the getWheel method — e.target.blur(); Kindly try this once.

9 Answers 9

Simplest answer:

 document.activeElement.blur()> /> 

Either of these can be used either in a functional or in a class component.

You can blur the field on onWheel handler. Something like this

I had the same problem, except I was working on desktop version only. To blur the focus on the input as suggested in other answers works to stop the scrolling. But it wasn’t what I wanted. I still want the user to be able to change the input with the keyboard.

So to disable scrolling on in React I added an onFocus property as follows:

 e.target.addEventListener("wheel", function (e) < e.preventDefault() >, < passive: false >)> /> 

It worked fine for me. I hope it helps others.

I solved this using a functional component that wraps the input element and adds an event listener for «wheel» and prevents default behavior. I find this preferable to using blur() which may have undesirable UX.

// Simply a wrapper for that disables scrolling to increment import < useEffect, useRef >from "react"; export const NumberInput = (props) => < const quantityInputRef = useRef(null); useEffect(() => < const ignoreScroll = (e) =>< e.preventDefault(); >; quantityInputRef.current && quantityInputRef.current.addEventListener("wheel", ignoreScroll); >, [quantityInputRef]); return type="number" />; >; 

In production, I actually use this component to disable scroll-incrementing for the component from material-ui instead of . I’ve used the native input in my example because that’s what the question was asking about.

I don’t think this is the best solution if you only want a numeric keyboard since there is a property that actually let you set whatever keyboard type you want, e.g. inputMode=»numeric»

Changing global events is not good practice and neither is blurring out of the field.

In react version you should use ref. Take a look at the example below :

import React, < Component, createRef >from "react"; class MyInput extends Component < constructor(props) < super(props); this.inputRef = createRef(); >onWheel = () => < this.inputRef.current.blur(); >; render() < return ( 
My input number : onWheel= />
); > > export default MyInput;

Thanks @Sephyre for above code, This worked fine but due to blur() method it is not user friendly. As I roll mouse wheel it looses focus and for input I have to click again in the input field to add a number.

Prevent onWheel’s event
 const inputElem = useRef(); onWheel=  < e.preventDefault(); inputElem.current.blur(); >> 
import < useRef >from "react"; import "./styles.css"; export default function App() < const inputElem = useRef(); const handleOnWheel = (e) =>< // if not use preventDefault, it is working e.preventDefault(); // The blur event fires when an element has lost focus. The event does not bubble, inputElem.current.blur(); >; return ( 
type="number" placeholder="type num" // prevent scroll on number input onWheel= />
); >

Does not work in Firefox, I can still change the number with the scroll wheel in the provided sandbox

I’ve updated the codesandbox and answer as well, pls try and check it out. I hope it is working welllll. Thanks

If you want to remove this scroll feature from all the number input fields of your project as whole or alternatively you could only import it into your component and this is the solution that worked for me.

First you create a custom hook like this one in your desired location in your project.

import < useEffect >from 'react'; const DisableNumInputScroll = () => < const handleWheel = (event) => < const < type >= event.target; if(type === 'number') < event.preventDefault(); >> useEffect(() => < document.addEventListener('wheel', handleWheel, < passive: false >); return () => < document.removeEventListener('wheel', handleWheel); >; >, []); return null; >; export default DisableNumInputScroll; 

Basically this adds a wheel event listener to the document and when the event occurs, it is checked if target of that event element is of type number. If yes, it will stop the default behavior which is responsible for the scroll increasing the number in input tag.

You can use this custom hook in your main App.js file like so,

import DisableNumInputScroll from './DisableNumInputScroll'; const App = () => < return ( <>  ); >; export default App; 

Источник

Input scroll when typing

Is it possible to prevent that kind of thing: I click on input, scroll down somewhere and when I type scroll jumps to input. I want prevent that jump. Thanks in advance.

3 Answers 3

I would suggest not using this solution, as you might run into alot of compatibilty problems, you don’t wan’t to solve.

But you could add an keydown eventlister to your inputelement, which prevents the default action if the keyIdentifier starts with «U+» (this way insert etc. will work)

Then you create a string from the events, keyCode value make it lowercase if the shift key wasn’t pressed, and insert it at the Cursors position.

inputElement.addEventListener ("keydown",function (e) < var key = e.keyCode || e.which; var element = e.srcElement || e.target; var ident = 0 | parseInt ( e.keyIdentifier.slice (-4) , 16) var cursorPos = element.selectionStart || 0; var selectionEnd = element.selectionEnd || 0; if (key < 31 || key >127 || ident !== key || e.ctrlKey || e.metaKey ) < return true >; if (key > 46 && key < 59 && e.shiftKey ) < key ^= 16; >if ( "U+" === e.keyIdentifier.slice (0,2) ) < //We only wan't to target text input values e.preventDefault() ; //this prevents the default action and with it the scrolling var characters = element.value.split (""); characters.splice (cursorPos,selectionEnd - cursorPos, String.fromCharCode (key)["to" + (e.shiftKey?"Upper":"Lower") + "Case"]()); element.value = characters.join (""); //append the string value to the input cursorPos++; if(element.createTextRange) < var range = element.createTextRange(); range.move('character', cursorPos); range.select(); >else < if(element.selectionStart) < element.focus(); element.setSelectionRange(cursorPos, cursorPos); >else < element.focus(); >> > >); 

So this is the updated version.

Known issues: Shift + 0 -> `" "` Shift + 3 -> `"#"` May not work on IE. 

And there might be alot more. If there is an ismpler approach, i would use it, as this might need alot of compatibility code for different keyboard layouts.

But it’s something to begin with

Источник

Prevent default scroll to element for input

Why would you want to prevent the behaviour? Are people supposed to guess what they’re typing in? Not everyone is a 400wpm touch-typist.

It’s not exactly what you’re asking but you could capture input on the document level then alter the value of your input element using those keystrokes. Not sure why you’d want to but it should work.

I have more complex logic on my site. First I simply want to prevent it, do some actions and programmatically call focus on input.

I would say this is not possible, because you are trying to break something all browsers, and maybe OS’ do by default, aka bad UX idea

3 Answers 3

position : fixed; will avoid the automatic scroll to input as it won’t be in the scrollable area.

Here is a fast written example, based on this answer, and using jQuery, sorry…

 var inputTop, inputBottom; window.onload = function() < inputTop = $('#input').offset().top inputBottom = inputTop + $('#input').height(); >function isScrolledIntoView(el) < var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); return ((inputBottom = docViewTop)); > function hideInput() < var el = $('#input'); if ( isScrolledIntoView(el) )< el.removeClass(); >else< el.addClass('hiddenInput'); el.css(); > > window.onscroll = hideInput; 

Thank you very much! I tried so many things and encountered so many problems with my invisible input, but this did the trick for stopping the page scroll when I change the input.

I also cannot think of this as good design. But we all have to do something our way. Try below script if it helps

$('input[type="search"]').on("keypress", function(event)< event.preventDefault(); return false; >); 

This will allow to keep focus on input box and browser will also not scroll to input box. If you want it cross browser you might need to handle keydown event as well. Let me know if you face any issue in handling other events.

But it will prevent you from typing any value in the input at any moment in any input : then blur is easier

Источник

Disable scroll on all inputs type number

With the help from this question: How to disable scrolling temporarily? it was pretty easy to make a working concept:

var keys = ; // Select all input elements var inputElems = document.getElementsByTagName('input'); // Turn them into an array inputElems = Array.prototype.slice.call(inputElems); // Create event listeners for input elements where type equals number inputElems.forEach(function(elem) < if(elem.type.toLowerCase() == 'number') < elem.addEventListener('focus', disableScroll, false); elem.addEventListener('blur', enableScroll, false); >>); function preventDefault(e) < e = e || window.event; if (e.preventDefault) e.preventDefault(); e.returnValue = false; >function preventDefaultForScrollKeys(e) < if (keys[e.keyCode]) < preventDefault(e); return false; >> function disableScroll() < if (window.addEventListener) // older FF window.addEventListener('DOMMouseScroll', preventDefault, false); document.addEventListener('wheel', preventDefault, ); // Disable scrolling in Chrome window.onwheel = preventDefault; // modern standard window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE window.ontouchmove = preventDefault; // mobile document.onkeydown = preventDefaultForScrollKeys; > function enableScroll() < if (window.removeEventListener) window.removeEventListener('DOMMouseScroll', preventDefault, false); document.removeEventListener('wheel', preventDefault, ); // Enable scrolling in Chrome window.onmousewheel = document.onmousewheel = null; window.onwheel = null; window.ontouchmove = null; document.onkeydown = null; >

When focus is on one of the input fields with a number type, it will disable scrolling. On blur it’ll enable it again. Please keep in mind that this will not prevent a user from manually dragging a scrollbar down with the mouse. It’s impossible to disable that.

Источник

Оцените статью