Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
JavaScript - img caption to appear/disappear onclick event

I need to have image caption to appear on 1 mouse click and disappear on next click by using JS. I can't figure out why the image caption is not appearing when I click on the image with onclick event and function use on external JS. Sorry if I make any mistake on question as this is my first post on the forum.

HTML

<div id="section1" >
        <h1>Pictures from my vacation</h1>`enter code here`
        <figure style="float: left;" >
            <img src="Photos/p1.jpg" title="Beach" value="hide/show" onclick="showOrHide()">
            <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
        </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.                                                                                                                                                                                         
    </p>
</div>

JS

function showOrHide() {

if (show=="false") {

document.getElementById("showthis").style.visibility="visible";
show="true";
    
}
else {
//show is true
document.getElementById("showthis").style.visibility="hidden";
show="false";
}

}

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

A few things to get you on your way:

  1. I wouldn't use onxyz-attribute-style event handlers. They can only call global functions, passing parameters to them is difficult because of handling text inside JavaScript code inside an HTML attribute, and various other things. I'd use modern event handling like addEventListener.

    But if you did want to use an onclick attribute for this, I'd use onclick="showOrHide(this)" (this will refer to the image that this click was on) and then accept an img parameter in the function, rather than using an id to do the lookup.

  2. Boolean values like true and false don't go in quotes.

  3. You don't seem to have declared your show variable anywhere.

  4. I'd use a class rather than directly modifying the style of the element.

So with all that in mind:

"use strict";

document.addEventListener("click", event => {
    const img = event.target.closest(".toggle-image");
    if (img && img.nextElementSibling.tagName === "FIGCAPTION") {
        img.nextElementSibling.classList.toggle("hidden");
    }
});
.hidden {
    visibility: hidden;
}
<div id="section1">
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;">
        <img src="Photos/p1.jpg" class="toggle-image" title="Beach" value="hide/show">
        <figcaption class="hidden">Waterton Beach</figcaption>
    </figure>
    <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.
    </p>
</div>

That code uses event delegation by hooking click on the document as a whole and then, when the click occurs, seeing if the click was on an .image-toggle element (or passed through when bubbling). If it did, it looks at the next element after the img to see if it's a figcaption and, if so, toggles a hidden class in the element's class list element to show/hide the caption.

(Those links are to MDN, which is an excellent resource for web programming information.)

about 4 years ago · Juan Pablo Isaza Denunciar

0

I've changed some things.

The html code:

<div id="section1" >
    <h1>Pictures from my vacation</h1>`enter code here`
    <figure style="float: left;" >
        <img id="myImage" src="https://logowik.com/content/uploads/images/526_liverpoolfc.jpg" title="Beach">
        <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
    </figure>
<p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.                                                                                                                                                                                         
</p>

I removed the inline onclick property, because it's better to add event listener in the JS like in the code below. With JS then we add the click listener and we check for the visibility value and we either show or hide it.

The JS code:

const myImage = document.getElementById("myImage")
const caption = document.getElementById("showthis")
myImage.addEventListener("click", () => {
 if(caption.style.visibility == "visible") {
  caption.style.visibility = "hidden"
 } else {
  caption.style.visibility = "visible"
 }

})

This is doing the toggle functionality. If you want the caption to be over the image, this is a matter of CSS.

about 4 years ago · Juan Pablo Isaza Denunciar

0

If displaying/hiding the caption is only your goal, then try this code. This should work.

<div id="section1" >
   <h1>Pictures from my vacation</h1>
   <figure style="float: left;" >
      <img src="https://picsum.photos/200/300" title="Beach" onclick="showOrHide()">
      <figcaption id="showthis"  style="visibility: hidden;">Waterton Beach</figcaption>
   </figure>
   <p>Beautiful and Sunny day at Wateron last year. Taking Ferry to explore around the late and natural beauty surrounded there. It was a beatiful day and beach and small town with full of visitors. Hope to back to this beautiful small town on summer break.                                                                                                                                                                                       
   </p>
</div>

Javascript function should be like this.

function showOrHide() {
    const visibility = document.getElementById("showthis").style.visibility;
    if (visibility == "hidden") {
        document.getElementById("showthis").style.visibility = "visible";
    } else {
        document.getElementById("showthis").style.visibility = "hidden";
    }
}

In case you want this javascript function to take care multiple images, you can modify the function like this. and in html on img tag pass the event into function showOrHide(event)

function showOrHide(e) {
    const img = e.target;
    const figcaption = img.nextElementSibling;
    const visibility = figcaption.style.visibility;
    if (visibility == "hidden") {
        figcaption.style.visibility = "visible";
    } else {
        figcaption.style.visibility = "hidden";
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda