Skip to content
Advertisement

Swap image with JavaScript

I made a small script for when someone clicks on this eye image the input type was changed from ”password” to ”text”

function mostrarocultarsenha() {
  var senha = document.getElementById("senha")
  
  if (senha.type == "password") {
    senha.type = "text";
  } else {
    senha.type = "password"
  }
}
<div class="campo">
  <label for="password"><strong>Senha</strong></label>
  <input type="password" name="senha" id="senha" required></input>
</div>

<img class="olho" id="olho" src="https://via.placeholder.com/100" onclick="mostrarocultarsenha()">

Photo from my website

I want that when the input changes from password to text, the image also changes from an eye to an eye with a scratch, and then if clicked again, go back to normal eye, does anyone know how I can do this?

Advertisement

Answer

basically it’s just a element ID src it’s actually really simple

<div class="campo">
  <label for="password"><strong>Senha</strong></label>
  <input type="password" name="senha" id="senha" required></input>
</div>

<a onclick="mostrarocultarsenha()"><img class="olho" id="olho" src="assets/closedEye.png"/></a>

function mostrarocultarsenha() {
  var senha = document.getElementById("senha")
  
  if (senha.type == "password") {
    senha.type = "text";
    document.getElementById("olho").src = "assets/openedEye.png";
  } else {
    senha.type = "password"
    document.getElementById("olho").src = "assets/closedEye.png";

  }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement