[Normaltic's 취업반 과제] 비밀번호 Visibility Toggle

2024. 4. 29. 16:29정보보안 및 해킹/Normaltic's 취업반 과제

my_page.php

[생략]

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" />

[생략]

<input type="password" name="userpassword" value="<?php echo htmlspecialchars($row['password']); ?>" readonly="readonly" id="password"/>

<i class="bi bi-eye-slash" id="togglePassword"></i><br>

<script>
    window.addEventListener("DOMContentLoaded", function () {
  const togglePassword = document.querySelector("#togglePassword");

  togglePassword.addEventListener("click", function (e) {
    // toggle the type attribute
    const type =
      password.getAttribute("type") === "password" ? "text" : "password";
    password.setAttribute("type", type);
    // toggle the eye / eye slash icon
    this.classList.toggle("bi-eye");
  });
});

</script>

[생략]

본의아니게 js를 사용하게 되었지만.. 일단 눈 아이콘 두개(보일 때, 안 보일 때)가 필요하니

https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css

로 일단 아이콘이 있는 css를 읽어와준다.

해당 css에는 이미 form i라는 것이 선언 및 정의되어 있기 때문에

<i class="bi bi-eye-slash" id="togglePassword"></i><br>

로 눈 아이콘을 넣어주고

<script>
    window.addEventListener("DOMContentLoaded", function () {
  const togglePassword = document.querySelector("#togglePassword");

  togglePassword.addEventListener("click", function (e) {
    // toggle the type attribute
    const type =
      password.getAttribute("type") === "password" ? "text" : "password";
    password.setAttribute("type", type);
    // toggle the eye / eye slash icon
    this.classList.toggle("bi-eye");
  });
});

</script>

이벤트 리스너를 통해 아이콘을 클릭했을 때 아이콘이 바뀌면서

<input type="password" name="userpassword" value="<?php echo htmlspecialchars($row['password']); ?>" readonly="readonly" id="password"/>

password라는 id가 있는 text의 type을 password였으면 text로, text였으면 password로 바꿔주는 작업을 진행한다.