Home > Software design >  JavaScript - img caption to appear/disappear onclick event
JavaScript - img caption to appear/disappear onclick event

Time:02-11

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

}

CodePudding user response:

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"  title="Beach" value="hide/show">
        <figcaption >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.)

CodePudding user response:

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.

CodePudding user response:

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

CodePudding user response:

Instead of adding a click event to image. Try with adding an event listener to the image.

HTML

 <div id="section1">
  <h1>Pictures from my vacation</h1>
  `enter code here`
  <figure style="float: left;">
    <img
      src="https://images.unsplash.com/photo-1644550805208-54b031553153?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1228&q=80"
      title="Beach"
      value="hide/show"
      
    />
    <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

let show = false;
const beachImg = document.querySelector(".beach-img")
beachImg.addEventListener("click", function () {
 if (show === false) {
   console.log("showing");
   document.getElementById("showthis").style.visibility = "visible";
   show = true;
} else {
   //show is true
   console.log("hiding");
   document.getElementById("showthis").style.visibility = "hidden";
   show = false;
}

});

Here's the working example.

  • Related