Home > database >  Swap image with JavaScript
Swap image with JavaScript

Time:04-23

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 >
  <label for="password"><strong>Senha</strong></label>
  <input type="password" name="senha" id="senha" required></input>
</div>

<img  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?

CodePudding user response:

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

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

<a onclick="mostrarocultarsenha()"><img  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";

  }
}

CodePudding user response:

const olho = document.querySelector("#olho")

if (senha.type === "password") {
   senha.setAttribute("type", "text")
   olho.src = "image link/path"
} else {
   senha.setAttribute("type", "password")
   olho.src = "another image link/path"
}

w3schools

  • Related