javascripthtmlpasswordstoggle

Placing password visibility icon inside password field


I have this following code.

<div class="login-password">
    <label for="password" class="form-label">Enter your password</label>
    <input id="loginPassword" type="password" class="form-control" placeholder="Enter your password" />
    <i class="bi bi-eye-slash" id="togglePassword" style="margin-left: -30px; cursor: pointer" ></i>
</div>

When I do this the password visibility icon is placed as in the image given below.

enter image description here

How do I place the visibility icon within password field.


Solution

  • I found the answer to my own question. Well, we have to group the input and the icon is the way to do it, and below is the code.

    .input-group-addon i {
        margin-left: -30px;
        cursor: pointer;
        z-index: 200;
        position: absolute;
        font-size: large;
        color: #6c757d;
    }
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" />
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-sRIl4kxILFvY47J16cr9ZwB07vP4J8+LH7qKQnuqkuIAvNWLzeN8tE5YBujZqJLB" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js" integrity="sha384-FKyoEForCGlyvwx9Hj09JcYn3nv7wiPVlz7YYwJrWVcXK/BmnVDxM+D2scQbITxI" crossorigin="anonymous"></script>
        
    <div class="login-password">
      <label for="password" class="form-label">Enter your password</label>
      <div class="input-group">
        <input
          id="loginPassword"
          type="password"
          class="form-control"
          placeholder="Enter your password"
        />
        <div class="input-group-addon">
          <i class="bi bi-eye-slash" id="togglePassword"></i>
        </div>
      </div>
    </div>