DEV Community

ktr92
ktr92

Posted on • Updated on

[html css js] Show/hide password input value

Codepen demo: https://codepen.io/ktr92/pen/vYVmbam

Solution example:

HTML

<div class="inputpassword" data-toggleblock="password">
  <input type="password">
  <img src="https://ktr92.github.io/nft/dist/img/Invisible.svg" alt="" data-togglebutton="password" class="password_invisible">
  <img src="https://ktr92.github.io/nft/dist/img/Eye2.svg" alt="" data-togglebutton="password" class="password_visible">
</div>
Enter fullscreen mode Exit fullscreen mode

CSS

.inputpassword {
  position: relative;
  width: 320px;
}

.password_visible {
  display: none;
}

.inputpassword.active .password_invisible {
  display: none;
}

.inputpassword.active .password_visible {
  display: block;
}

.inputpassword img {
  position: absolute;
  right: 0;
  top: 50%;
  cursor: pointer;
  transform: translateY(-50%);
}

input {
  background: #f3f5f8;
  padding: 20px;
  border-top-right-radius: 10px;
  border-top-left-radius: 10px;
  border: none;
  border-bottom: 4px solid #d9dde3;
  display: block;
  width: 100%;
  font-style: normal;
  font-weight: 500;
  font-size: 20px;
  line-height: 1;
  resize: none;
  color: #212531;
}
Enter fullscreen mode Exit fullscreen mode

JS

document.querySelectorAll('[data-togglebutton="password"]').forEach((item) => {
  item.addEventListener("click", (event) => {
    let inp = item.closest("[data-toggleblock]").querySelector("input");
    if (inp.type === "password") {
      inp.type = "text";
      item.closest("[data-toggleblock]").classList.add("active");
    } else {
      inp.type = "password";
      item.closest("[data-toggleblock]").classList.remove("active");
    }
  });
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)