Prevent scrolling within input field

I have a text entry field with background images that separate each letter into its own box.

Unfortunately, an issue arises when I reach the end of the input: the view automatically scrolls down because the cursor is positioned after the last letter entered.

The complication

Is there a way to prevent this automatic scrolling behavior in my text inputs?

I've attempted using "overflow:hidden" and setting a "maxlength", but the problem still persists.

Edit: here's a simple demonstration (I want to eliminate the shifting effect when the 4th letter is typed)

Answer №1

There are 2 possible solutions:

CSS Method

To avoid the 'jump' behavior, you can increase the width of your input slightly. Example: width : 202px

View CSS solution on JSFiddle

JavaScript Approach

If adjusting the width is not an option, you can prevent the keypress event and check the length of the input value. If it is less than 4 characters, allow the input; otherwise, do nothing.

Using jQuery:

var t = $('#input-form');
t.keypress( function(event){
    //Prevent the value from being added
    event.preventDefault();
    //Regex to determine allowed characters (alphanumeric & underscore in this case)
    var reg = /\w/g;
    //Get the key pressed
    var inputChar = String.fromCharCode(event.which);
    //Get the length of the input's value
    var inputLength = t.val().length;

    if ( reg.test(inputChar) && (inputLength < 4) ) {
        //Add the value if input length is less than 4
        t.val(t.val() + inputChar);
    }else{
        //Do nothing if conditions are not met
        return;
    }
});

View jQuery solution on JSFiddle

Pure JavaScript Method:

var t = document.getElementById('input-form');

t.addEventListener('keypress', function(event){
    //Prevent the value from being added
    event.preventDefault();
    //Regex to determine allowed characters (alphanumeric & underscore in this case)
    var reg = /\w/g;
    //Get the key pressed
    var inputChar = String.fromCharCode(event.which);
    //Get the length of the input's value
    var inputLength = t.value.length;
    if ( reg.test(inputChar) && (inputLength < 4) ) {
        //Add the value if input length is less than 4
        t.value = t.value + inputChar;
    }else{
        //Do nothing if conditions are not met
        return;
    }
});

View Pure JavaScript solution on JSFiddle

Answer №2

I've updated the field width in your CSS code as per your request, here is the revised code:

input {
width: 205px;
height: 50px;
font-size: 30px;
font-family: "Courier", monospace;
letter-spacing: 28px;
text-indent: 18px;
position: fixed;
padding: 0;
margin: 0;
white-space: nowrap;
overflow: hidden;

}

Go ahead and test it by typing something now and observing the fourth character.

Feel free to reach out if you need any further assistance.

Regards, Sohail.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error trying to access the length property of an undefined variable while passing props

I need help with my shopping app project. I am trying to create a feature where if the cart is empty, it should display a message saying "shopping cart is empty." However, when I try to implement this, I keep getting a type error that says "Cannot read p ...

When the screen is at mobile width, elements with the class "Responsive" are hidden using the display:none; property. These elements can be

Hey there! So, I've got this cool interactive banner on my website. It features 2 slider sections with some awesome products on the right side. The layout is responsive, meaning that when you switch to a mobile screen size (around 515px or less), the ...

Initiate modal from sub-component

Right now, I am developing a vue application with a structure that closely resembles the following: <div class="characters"> <Character v-for="character in this.charactersToSearch" :key="character.id" :name="cha ...

Convert Ajax null value to NoneType in web2py

Every time I save information on a page, an AJAX request is sent with all the necessary data to be stored in the database. The format of this data looks similar to this example: {type: "cover", title: "test", description: null, tags: null} However, when ...

"Using axios and async/await in VUE.JS to perform multiple asynchronous GET

Perhaps this is a somewhat basic inquiry, as I am still learning the ropes of vue.js and javascript. Please bear with me if my question is not well-articulated or if the solution is straightforward... I am facing an issue where I need to retrieve data from ...

Counting radio buttons in AngularJS and handling undefined values when passing parameters

After spending countless hours trying to figure out how to count radio buttons, I encountered another issue where the value passed to ng-change would become "undefined". My question is, how can I successfully pass that value? Any assistance with counting o ...

Importing a library dynamically in Next.js

I'm currently facing a challenge in dynamically importing a library into one of my next.js projects. The issue arises when I don't receive the default export from the library as expected. Initially, I attempted to import it the next.js way: impo ...

Ways to ensure all images have been successfully uploaded to Firebase before executing a function

Here's a function I've created that takes image URIs from the state, uploads them to Firebase Storage, and then updates the state with the download URLs: uploadImages = async (userID) => { // Loop through each image for (var index = 0 ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

responsive cascading dropdown.. preassigned value

I've come across this interesting script on a website and it's been working pretty well for me so far. The script can be found at the following link: . However, I have a specific requirement when it comes to setting a certain value for the catego ...

unable to retrieve data using ajax

Having some trouble with my ajax code that is supposed to print values: success: function(returndata) { $('#first').html("<div id='first' class='progress-bar progress-bar-primary' role='progressbar' aria-valu ...

Modify the information on a page by clicking a button on a different page

I'm currently working on the design of a website that consists of two pages. The first page features a button, which when clicked should remove the hidden class from an element on the second page. I have searched extensively for a solution, but so far ...

Developing a collection of reusable components in a Javascript bundle for enhanced efficiency

I currently have a backend rendered page (using Django) that I want to enhance by incorporating components from PrimeVue and a markdown editor wrapped as a Vue component. Previously, we utilized some simple animations with jQuery which we included directly ...

Despite receiving a 404 fetch response, the page still exists

I have encountered an issue with my Fetch code (POST) where the response shows status: 404 even though the URL returns a JSON when accessed through the browser. Surprisingly, changing the URL to https://httpbin.org/post brings back normal data. Furthermore ...

When you try to click outside of react-select, the dropdown doesn't

I've been working on customizing react-select and encountered some issues. Specifically, after modifying the ValueContainer and SelectContainer components, I noticed that the dropdown doesn't close when clicking outside of it after selecting a va ...

retrieve Excel document via POST request

I have a scenario where my API endpoint accepts JSON input and returns an Excel file directly instead of providing a link to download the file. How can I use JQuery AJAX to download this file? Here is the backend code snippet: public function postExcel() ...

Graph your data with a stunning Fusioncharts area range graph combined with a sleek

My goal is to create a visual representation of an area range graph with a corresponding mid line. You can view the image below for reference: https://i.sstatic.net/8KDbF.png While I have successfully incorporated the low and high values, I am encounterin ...

What is the best way to iterate through a puppeteer selector's response in a loop?

So, by using page.evaluate I can accomplish the following: await page.evaluate(function() { var links = document.querySelectorAll('a'); for (var i = 0; i < links.length; i++) console.log(links[i].href); }); However, I am interested in a ...

How to retrieve the length of data in Angular without relying on ng-repeat?

I am currently working with Angular and facing a challenge where I need to display the total length of an array without using ng-repeat. Here is the situation: I have a default.json file: { { ... "data": [{ "name":"Test", "erro ...

Steps for displaying a loading image during the rendering of a drop-down list (but not during data loading):

Using jQuery's autocomplete combobox with a large dataset of around 1,000 items. The data loads smoothly from the server, but there is a delay when expanding the drop-down list to render on screen. Is there a way to capture the initial click event on ...