1
I did an exercise using pure javascript, the exercise asked you to click on an image of a lamp "erased" and, soon after it was clicked on this image, the attribute "src"
of it changed and received another image, which would be the same image of the lamp "lit". I managed to accomplish, however it works only once, after I click it does not change again.
My question is, how can I verify when an element (in this case an image) was clicked using pure javascript only ? My idea would be to take how many times the image was clicked and change the "src
" of hers in a loop
.
here’s the ex I did but it works only once:
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
<img src="lampada_Apagada.jpg" id="imagem"
onclick="acendeLampada()">
<img src="lampada_Acesa.jpg" id="imagem2" onclick="apagaLampada()">
</div>
<script src="lampada.js" type="text/javascript"></script>
</body>
</html>
Javascript code:
function acendeLampada() {
let lampada = document.getElementById('imagem').src =
'lampada_Acesa.jpg'
}
function apagaLampada() {
let lampada = document.getElementById('imagem2').src =
'lampada_Apagada.jpg'
}
Thank you very much !
– Pedro