How can I keep the cursor from automatically moving to the beginning of an input field when the type changes?

Currently in the process of creating a Password field that allows users to hide or display their password in React/Ionic.

  • I am aiming to maintain focus on the password field when switching the input type, similar to how it is done on the PayPal Login page. I achieve this by using event.preventDefault() on the mousedown event.

const input = document.querySelector('input')

function toggleVisibility() {
  if (input.type === "text")
    input.type = "password"
  else
    input.type = "text"
}

function keepFocus(event) {
  event.preventDefault()
}
<input placeholder="Password" type="text">
<button onmousedown="keepFocus(event)" onclick="toggleVisibility()">Show Password</button>

Issue

  • After switching the input field type, the cursor jumps back to the beginning of the input field. I would like to retain the cursor position as it was before the change. (Similar to the behavior on PayPal)

Answer №1

Upon reviewing the code provided by PayPal, it is evident that the functionality can be achieved by simply calling input.focus() within a single event-listener:

      function hidePassword(e) {
          if (baseType === 'tel') {
              $(field).addClass('tel-password');
          } else {
              field.setAttribute('type', 'password');
          }
          $(btnShow).removeClass('hide');
          $(btnHide).addClass('hide');
          field.focus();
          e.stopPropagation();

          login.logger.log({
              evt: 'is_pwd_sh',
              data: 'N',
              instrument: true
          });
          login.logger.pushLogs();
      }

My modified example below streamlines this process with some adjustments:

  • It is recommended to set the default type="" as password. This ensures that users do not accidentally reveal their password while typing in public settings such as screen-sharing or giving presentations.
  • The use of embedding the target
    <input type="password" />
    within
    <button data-for="" />
    eliminates potential issues caused by early calls to querySelector or getElementById before the DOMContentLoaded event.
  • Unnecessary calls to event.stopPropagation() or event.preventDefault() should be avoided. The focus should solely be on invoking input.focus() in conjunction with changing the HTMLInputElement.type property.
  • Avoid using onmousedown with buttons as it limits interactions. Instead, rely on the more versatile 'click' event for various user inputs like mouse, keyboard, and touch-based actions.

In summary, here is a simplified version of the script:

function toggleVisibilityOnClick( event ) {
    
    const button = event.currentTarget;
    const input = document.getElementById( button.dataset['for'] );
    if( !input ) throw new Error( "Couldn't find password input." );
    
    if( input.type === 'text' ) {
        input.type = 'password';
    }
    else {
        input.type = 'text';
    }

    input.focus();
}
<input placeholder="Password" type="password" id="pwdInp" />
<button data-for="pwdInp" onclick="toggleVisibilityOnClick(event)">Show Password</button>

If using Microsoft's browsers which support -ms-reveal, the toggle becomes redundant, and therefore should be hidden under these circumstances:

@supports selector(::-ms-reveal) {
    
    input[type="password"] + button[data-for] {
        display: none;
    }
}

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

Enhance the worth of text box

Is there a way to adjust the value of a textbox by one on keyup, keydown, or tap events? Check out this example. Here is the HTML structure: <div class="right-content" id="rc-0" style="height: 250px;"> <div class="right-cont-main" id="rcm-0" s ...

Exploring the Firebase authentication and implementing public and private routing in a React project

I am currently working on incorporating Public and Private routes using react-router-dom in my react application. To retrieve the authentication state, I am utilizing the firebase.auth().onAuthStateChanged() function. The issue arises because the firebase ...

The response from Axios in NodeJs is displaying incorrect encoding

Having some trouble executing a REST call using Axios and receiving an unexpected response. try { const response = await axios.get("https://api.predic8.de/shop/products/"); console.log(response.data); } catch (error) { console.log(`[Error] -> ...

Ensuring a @keyframe animation remains constant for the entire duration of the user's visit to the webpage using CSS

How can I create a continuous @keyframe animation that stays active for the duration of the user's visit to my webpage? I've implemented several color animations on my website, each with a specific duration. Is there a way to make these color ch ...

Modify data in a table using Dialog Component in Angular Material

I need to implement a Material Dialog feature that allows users to update entries in a table by clicking on the "Change Status" button. Check out this functional snippet: https://stackblitz.com/edit/angular-alu8pa I have successfully retrieved data fr ...

The Electron/React/Typescript module is missing: Error: Unable to locate 'fs' in the /node_modules/electron directory

Within my Electron application, I have a file named App.ts. It contains the following code snippet: import { ipcRenderer } from 'electron'; // remaining code However, during the app development process, I encountered this error message: Error: ...

Angular2: the setTimeout function is executed just a single time

Currently, I am working on implementing a feature in Angular2 that relies on the use of setTimeout. This is a snippet of my code: public ngAfterViewInit(): void { this.authenticate_loop(); } private authenticate_loop() { setTimeout (() =& ...

Exploring the plane intersection within a 3D object using Three.js

I attempted to create an animation using Three.js to display the intersection plane on a 3D object with the following code snippet: import React, { useRef, useEffect, useState } from 'react'; import * as THREE from 'three'; export cons ...

Learn the steps for filling the color area between two points in HighCharts

Is it possible to have a color fill between two points on an area chart when clicked? You can view the current chart here. $(function () { $('#container').highcharts({ chart: { type: & ...

Guide to implementing personalized validation for an angular component

In my Angular component, I am looking to implement a custom input validator. However, I am facing an issue while trying to access the ngModelController in the $onInit function. It seems that the form is not populated at this stage. Strangely, in the sendEm ...

`In NodeJS, facing a challenge with implementing a many-to-many relationship using Sequelize's

I'm in the process of setting up many-to-many relationships between roles and accesses. The `roles` table will contain a list of roles (admin, developer, etc...) and the `accesses` table will have a list of permissions (Create Project, Create Site, De ...

Is utilizing both an HTTP-only cookie and a token an ideal combination for enhancing security

Hello, I am currently exploring the concept of managing authentication on the client side using the HTTP-only cookie provided by the server. My main confusion stems from the fact that the front end is unable to access the HTTP-only cookie. How then does ...

Utilizing Material UI with React Router to create a navigational menu with NavLink

I'm a beginner in React and I'm using UI Material for the design of my application, which is divided into three parts: Nav, Header, and Content. In the Nav, I have placed the links, but when I click on a link, the information is displayed in the ...

Send all requests made to /api/.. to express

I have configured an nginx server with a react app as the frontend and an express server serving as the backend. The express server is running on localhost:5000/ server { listen 80 ; server_name siteurl; server_name siteip; # SSL con ...

What is the best way to implement conditional styling in Vue.js?

Looking to incorporate a conditional style into my Component. Here is my component: <site-pricing color="primary" currency="$" price="25" to="/purchase" > <template v-slot:title>Complete</templat ...

How can I retrieve the children of a component in React?

Currently, I am working on implementing Class Components for a project involving a main picture and a smaller pictures gallery stored in an array. The overall structure consists of an all pictures container that houses both the main picture and smaller pic ...

Error: Unable to locate module: 'cats.png' in the '/public/img' directory within Next.js

I am trying to implement the img tag in my Next app, but it doesn't seem to be working. This is how I have coded the img tag: <img src={'/public/img/cats.png'} alt="cats img" /> Despite searching extensively, I have been una ...

transferring the value of a textbox into another textbox

I am trying to extract the value from one textbox and transfer it to another textbox. Here is my current code: <input type="text" value="Keyword" id="one" /> <input type="text" value="Search" id="two" /> <a href="#" id="btn">button</ ...

Challenges encountered with using TinyMce in Meteor React, specifically when working on iPad devices

I am currently working on an app with Meteor React that uses TinyMce through react-tinymce. I followed the instructions provided at The issue I am encountering is related to a form component with TinyMCE, which allows users to add comments. While it funct ...

Steps for setting the value of a textbox within a bootstrap popover

When a user clicks on an Anchor element, I am displaying a Bootstrap popover using the following JQuery code. Jquery $("[data-toggle=popover]").popover({ trigger: 'click', placement: "top", html: true, ...