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

247
Vistas
JavaScript: título de img para aparecer/desaparecer en el evento al hacer clic

Necesito que el título de la imagen aparezca con un clic del mouse y desaparezca con el siguiente clic usando JS. No puedo entender por qué el título de la imagen no aparece cuando hago clic en la imagen con el evento onclick y uso de la función en JS externo. Lo siento si cometo algún error en la pregunta, ya que es mi primera publicación en el foro.

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

función mostrar u ocultar () {

 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

Algunas cosas para ponerte en camino:

  1. No usaría onxyz -controladores de eventos de estilo atributo. Solo pueden llamar a funciones globales, pasarles parámetros es difícil debido al manejo de texto dentro del código JavaScript dentro de un atributo HTML, y varias otras cosas. Usaría el manejo de eventos moderno como addEventListener .

    Pero si quisiera usar un atributo onclick para esto, usaría onclick="showOrHide(this)" ( this se referirá a la imagen en la que estaba este clic) y luego aceptaría un parámetro img en la función, en lugar de usando una id para hacer la búsqueda.

  2. Los valores booleanos como true y false no van entre comillas.

  3. Parece que no ha declarado su variable show ninguna parte.

  4. Usaría una clase en lugar de modificar directamente el estilo del elemento.

Así que con todo eso en mente:

 "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>

Ese código utiliza la delegación de eventos al vincular el clic en el documento como un todo y luego, cuando se produce el clic, ver si el clic se realizó en un elemento .image-toggle (o se pasó cuando burbujeaba). Si lo hizo, mira el siguiente elemento después de img para ver si es un figcaption y, si es así, alterna una clase hidden en el elemento de la lista de clases del elemento para mostrar/ocultar el título.

(Esos enlaces son a MDN, que es un excelente recurso para obtener información sobre programación web).

about 4 years ago · Juan Pablo Isaza Denunciar

0

He cambiado algunas cosas.

El código HTML:

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

Eliminé la propiedad onclick en línea, porque es mejor agregar un detector de eventos en el JS como en el código a continuación. Con JS, luego agregamos el detector de clics y verificamos el valor de visibilidad y lo mostramos u ocultamos.

El código JS:

 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" }

})

Esto está haciendo la funcionalidad de alternar. Si desea que el título esté sobre la imagen, esto es una cuestión de CSS.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Si mostrar/ocultar el título es solo su objetivo, pruebe este código. Esto debería funcionar.

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

La función Javascript debería ser así.

 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"; } }

En caso de que desee que esta función de javascript se ocupe de varias imágenes, puede modificar la función de esta manera. y en html en la etiqueta img pase el evento a la función 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