Javascript button to change image

Asked

Viewed 20 times

0

I need to make a site that contains an image and a button. When the button is pressed the image should change.

I made a code, but it doesn’t work. I looked for everything and couldn’t find the answer to my question.

Follows the code:

function alterarImagem(img, flor.jpeg){
  document.getElementById("img").src = flor.jpeg; 
}   
*{margin: 0 auto; padding:0;}

body{
    background-color:black;
}

#dvCentro{
    width:200px;
    margin-top:50px;
    background-color: white;
    border:5px solid #821919;
    padding:6px;
    border-radius: 5px;
}
<html>
  <head>
    <title>exercicio 5</title>
    <meta charset="utf-8">
  </head>
  <body>
    <div id="dvCentro">
      <button onclick="alterarImagem('img', 'flor.jpeg');">
        Clique para trocar a imagem
      </button>
      <br />
      <div style="border-bottom:3px solid #000; padding:5px;"></div>
      <br />
      <img src="pqp.jpeg" alt="Imagem" title="Imagem" id="img" boarder="0px" width="200px" height="200px"/>
      <br />
    </div>
  </body>
</html>

1 answer

2

First you need to understand that by passing parameters to a function, in your case the Function alterarImagem, the parameters must be valid varietal names, and "flower.jpeg" is not a valid name (I suggest studying variable names in javascript), it should be something like:

function alterarImagem(img, nomeImagem) { 
    document.getElementById(img).src = nomeImagem;
}

So, in the event click while running alterarImagem('img', 'flor.jpeg'); Function will receive the correct values in the variables "img" and "image name"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.