How to display / hide text using an image as a button?

1

Hi, I'm setting up a small website where I wanted to use several images as a button that when clicking each displayed a different text, how can I do that?

I tested this one but it does not close the first text when opening the second, everything is mixed in the same space.

<div class="divspoiler">
<input type="image" src="IMAGEM AQUI" onclick="if (this.parentNode.nextSibling.childNodes[0].style.display != '') { this.parentNode.nextSibling.childNodes[0].style.display = ''; this.value = 'Ocultar'; } else { this.parentNode.nextSibling.childNodes[0].style.display = 'none'; this.value = 'Mostrar'; }" />
</div><div><div class="spoiler" style="display: none;">TEXTOOOOOO
</div></div>
    
asked by anonymous 14.10.2017 / 19:08

1 answer

3

An example that might help

//array de objetos que armazena o link das imagens e o texto de cada imagem,
        //pode ser um arquivo JSON externo
        var imgTexto = [
          {"img":"https://i.pinimg.com/736x/ae/d7/bc/aed7bcbe347a262f89cc3867cdce54c2--cutest-kittens-ever-cute-baby-animals.jpg",
          "txt":"Texto da Imagem 1"},
          {"img":"https://i.pinimg.com/736x/2e/51/4d/2e514d03b0414f8b7c5adefa5cbccba4--wink-wink-adorable-animals.jpg",
          "txt":"Texto da Imagem 2"}
        ];

        //variavel img armazena as strings das tags <img /> ja prontas para inserir no HTML
        // geradas pelo for que vem a seguir
        var img = "";

        //for percorre o array de objetos e cria tags<img /> formatadas para inserir no HTML
        for(var key in imgTexto) {
          img += "<img src='"+imgTexto[key].img+"' onclick='mostraTexto("+key+")' />";
        }

        //insere tags <img /> com todas as imagems do array na div com id="imgs"
        document.getElementById("imgs").innerHTML = img;

        //função que mostra o texto referte a imagem que possui a msm key
        function mostraTexto(key) {

          document.getElementById("texto").innerHTML = imgTexto[key].txt;
        }
img {
        border: 10px solid white;
        outline: 1px solid black;
        width: 150px;
        height: 150px;
      }
<div id="imgs"></div>
<div id="texto"></div>

I tried to make it well commented to help understanding. Click Run to see it working. so I understand that's what you're trying to do.

    
14.10.2017 / 20:03