Several ways to display images with interactive captions

I am in need of multiple image modals with different descriptions. Each image should have a unique caption that appears when clicked. I have searched for solutions that display alt text for each image, but I require it to show other specific texts upon clicking. Currently, I have set up multiple image modals, but they all open with the same caption.

Here is the JavaScript function:

function onClick(element) {

  document.getElementById("modal01").style.display = "block";

}

And here is the HTML code:


  <div class="container1">
    <img src="image1.jpg" style="max-width:100%;cursor:pointer"
    onclick="onClick(this)" class="modal-hover-opacity">
  </div>
  <div class="container1">
    <img src="image2.jpg" style="max-width:100%;cursor:pointer" 
    onclick="onClick(this)" class="modal-hover-opacity">

  </div>
  <div class="container1">
    <img src="image3.jpg" style="max-width:100%;cursor:pointer" 
    onclick="onClick(this)" class="modal-hover-opacity">

  </div>



<div id="modal01" class="modal" onclick="this.style.display='none'">
  <span class="close">&times;&nbsp;&nbsp;&nbsp;&nbsp;</span>
  <div class="modal-content">
    <img id="img01" style="max-width:100%">
    <div id="caption" style="color:white">This is the caption</div>
    <div id="2ndcaption" style="color:white">this is the 2nd</div>
    <div id="3rdcaption" style="color:white">This is the 3rd</div>
  </div>
</div>

Lastly, the CSS styles:

.modal {
z-index:1;
display:none;
padding-top:10px;
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
overflow:auto;
background-color:rgb(0,0,0);
background-color:rgba(0,0,0,0.8)
}

.modal-content{
margin: auto;
display: block;
    position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}


.modal-hover-opacity {
opacity:1;
filter:alpha(opacity=100);
-webkit-backface-visibility:hidden
}

.modal-hover-opacity:hover {
opacity:0.60;
filter:alpha(opacity=60);
-webkit-backface-visibility:hidden
}


.close {
text-decoration:none;float:right;font-size:24px;font-weight:bold;color:white
}
.container1 {
width:200px;
display:inline-block;
}
.modal-content, #caption {   

    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

Answer №1

here is a nifty solution for you

start by identifying the chosen image through the event triggered then locate the caption using its id (e.g., id="1stcaption") based on the attribute value of the img (like class or title) (in this case, it should be 1stcaption)

add another click eventlistener that triggers a "modal" click to hide the previously selected element and close the "modal"

alternatively, you can log everything to the console and figure it out ;)

javascript

function onClick(event) {

  const selectedElement = event.getAttribute("title")



  const allCaptions = document.getElementById(selectedElement)

  allCaptions.style.display = 'block';
  document.getElementById("modal01").style.display = "block";



  document.querySelector('.modal').addEventListener('click', function (event) {

    document.getElementById("modal01").style.display = "none";
    allCaptions.style.display = 'none';


  })



}

HTML

  <div class="container1">
    <img
      src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTczNTI2ODUwOF5BMl5BanBnXkFtZTcwMTU0NTIzMw@@._V1_SY1000_CR0,0,674,1000_AL_.jpg"
      style="max-width:100%;cursor:pointer" onclick="onClick(this)" class="modal-hover-opacity" title="1stcaption">
  </div>
  <div class="container1">
    <img
      src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTUyNzk3MjA1OF5BMl5BanBnXkFtZTcwMTE1Njg2MQ@@._V1_SY1000_CR0,0,674,1000_AL_.jpg"
      style="max-width:100%;cursor:pointer" onclick="onClick(this)" class="modal-hover-opacity" title="2ndcaption">

  </div>
  <div class="container1">
    <img
      src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTM0MDgwNjMyMl5BMl5BanBnXkFtZTcwNTg3NzAzMw@@._V1_.jpg"
      style="max-width:100%;cursor:pointer" onclick="onClick(this)" class="modal-hover-opacity" title="3rdcaption">

  </div>



  <div id="modal01" class="modal">
    <span class="close">&times;&nbsp;&nbsp;&nbsp;&nbsp;</span>
    <div class="modal-content">
      <img id="img01" style="max-width:100%">
      <div id="1stcaption" style="color:white; display : none">This is the caption</div>
      <div id="2ndcaption" style="color:white; display : none">this is the 2nd</div>
      <div id="3rdcaption" style="color:white; display : none">This is the 3rd</div>
    </div>
  </div>

Answer №2

There are countless methods to achieve the same goal. I put together a quick solution for your scenario.

Please note that the first step is to enable visibility using the attribute visible in the appropriate caption, and then disable it with the cleanAttribute() function on the close button.

I trust this will be of assistance to you.

function onClick(element) {
  let caption = 'caption'.concat(element.id.charAt(element.id.length - 1));
  document.getElementById("modal01").style.display = "block";
  document.getElementById("modal01").setAttribute("visible", caption)
  document.getElementById(caption).toggleAttribute("visible");  
}

function cleanAttribute(element) {
  if (element.hasAttribute("visible")) {
  let caption = element.getAttribute("visible");
  document.getElementById(caption).toggleAttribute("visible");  
  element.removeAttribute("visible")
  }
  
}
.modal {
z-index:1;
display:none;
padding-top:10px;
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
overflow:auto;
background-color:rgb(0,0,0);
background-color:rgba(0,0,0,0.8)
}

.modal-content{
margin: auto;
display: block;
    position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}


.modal-hover-opacity {
opacity:1;
filter:alpha(opacity=100);
-webkit-backface-visibility:hidden
}

.modal-hover-opacity:hover {
opacity:0.60;
filter:alpha(opacity=60);
-webkit-backface-visibility:hidden
}


.close {
text-decoration:none;float:right;font-size:24px;font-weight:bold;color:white
}
.container1 {
width:200px;
display:inline-block;
}
.modal-content, #caption {   

    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

div[visible] {
  display: block !important;
}
 <div class="container1">
    <img id="image1" src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTczNTI2ODUwOF5BMl5BanBnXkFtZTcwMTU0NTIzMw@@._V1_SY1000_CR0,0,674,1000_AL_.jpg" style="max-width:100%;cursor:pointer"
    onclick="onClick(this)" class="modal-hover-opacity">
  </div>
  <div class="container1">
    <img id="image2" src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTUyNzk3MjA1OF5BMl5BanBnXkFtZTcwMTE1Njg2MQ@@._V1_SY1000_CR0,0,674,1000_AL_.jpg" style="max-width:100%;cursor:pointer" 
    onclick="onClick(this)" class="modal-hover-opacity">

  </div>
  <div class="container1">
    <img id="image3" src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTM0MDgwNjMyMl5BMl5BanBnXkFtZTcwNTg3NzAzMw@@._V1_.jpg" style="max-width:100%;cursor:pointer" 
    onclick="onClick(this)" class="modal-hover-opacity">

  </div>



<div id="modal01" class="modal" onclick="this.style.display='none',cleanAttribute(this)">
  <span class="close">&times;&nbsp;&nbsp;&nbsp;&nbsp;</span>
  <div class="modal-content">
    <img id="img01" style="max-width:100%">
    <div id="caption1" style="color:white; display: none;">This is the caption</div>
    <div id="caption2" style="color:white; display: none;">this is the 2nd</div>
    <div id="caption3" style="color:white; display: none;">This is the 3rd</div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigate up to the ancestor element before moving back to the previous two sibling elements using Xpath

Here is an example of HTML code: <span class="state"> <label class="state button start" ...>"Start"</label> </span> <span class="name tracker_markup"> <span class="labels pre ...

Is it possible to utilize RedisJson to store express-session data in place of Redis?

I am currently attempting to access the express-session data manually without relying on req.session.reload() and req.session.save(). My aim is to utilize Redisjson instead of the default redis. The problem I am encountering is that the express-session set ...

Guide to executing a chain of parallel API calls with changing parameters using nodejs

I am working on a project that involves making multiple API calls while changing a single parameter value in the URL based on values stored in an array. Currently, I have about 30-40 values in the array and I am using NodeJS and Express for this task. Belo ...

Embracing Interfaces Over 'any' Types in TypeScript

https://i.stack.imgur.com/W6NMa.pngWould it be beneficial to utilize an interface as a variable type rather than opting for any? For instance, if I have 3 functions where I am declaring variables that can contain alphanumeric data, would defining them us ...

Why isn't the VueJS component loading state getting updated after Canceling an Axios network request?

Within my dashboard, there is a dropdown for filtering dates. Each time a user changes the dropdown value, multiple network requests are sent using Axios. To prevent additional API calls when the user rapidly changes the date filters, I utilize AbortContr ...

Is there a way to flip a figure that is flipped upside down?

I'm currently working on creating a map using a json file to go from d3.js to Three.js. However, when the map is displayed, it appears upside down. I'm wondering if there is a way to flip it so that it displays correctly. As a newcomer to d3 and ...

Dynamically insert letters into each row as the HTML table increases

How can I display dynamically increasing alphabets in a newly generated cell on the left side of each row, based on the option selected in a dropdown list? These alphabets will serve as bullet points or serial numbers for the text boxes in each row. View ...

Attempting to create a dynamic grid layout utilizing CSS to ensure optimal responsiveness

I am working on creating a webpage layout similar to the one in the link below: The maximum width for the layout is set to 1600px. However, I am facing challenges in making it fully responsive. This is because all the boxes are given widths in percentages ...

Display only the labels of percentages that exceed 5% on the pie chart using Chart JS

I'm currently diving into web development along with learning Chart.js and pie charts. In my project, the pie chart I've created displays smaller percentage values that are hardly visible, resulting in a poor user experience on our website. How c ...

Retrieving data using the GetJSON method consistently returns identical values

Here is the code I have written: $(document).ready(function () { $.getJSON("data.json", function (data) { var user_Data = ""; $.each(data, function (key, value) { user_Data += '<p class="user">' + value.na ...

A possible substitute for the "background-size" CSS attribute

After struggling for days without success, I find myself once again seeking your help. The current issue revolves around the slideshow on THIS website, which is powered by the jQuery Infinite Carousel Plugin. Despite adding background-size: auto 100%; to ...

Effective URL structure with nested ui-view in AngularJS

It is common knowledge that Angular functions as a SPA (Single Page Application). I am seeking the most effective approach to display a main left-side menu selector page, where clicking on any menu item will load the content in the right-side view div. Th ...

What are the distinctions in how jQuery behaves when an element is assigned to a variable versus in Javascript?

I've noticed that when I assign a jQuery element to a variable, it doesn't match the element in a comparison. However, if I assign a JavaScript element, it does... test1 = $(".the_div"); console.log(test1 == $(".the_div")); // This logs false ...

When using the mui joy library, obtaining the input value upon submission may result in the retrieval of an "unidentified" response

Struggling to fetch user input for 2FA authentication using the mui JoyUI library. Attempted using e.target and searching for input value with no success. Clearly missing something in the documentation. Also gave 'useRef' a shot, but the code sni ...

Tips for transferring input data to a static HTML page

After successfully identifying a value in a table using jQuery, I am faced with the challenge of passing it to a static HTML page. How can this transition be achieved smoothly? $('.gobutton').bind('click', function(){ var value = $( ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

How to send a PHP array to AJAX and show it on the webpage

Looking to enhance the interactivity of my website by showing icons (either correct or false) after users submit a registration form. This way, they can easily identify any incorrect fields. To achieve this, I understand that I'll need to utilize jso ...

Discover how to use Jest and Enzyme to test for any string as the defaultValue on an input field

As a beginner in the world of testing, I've been exploring the airbnb / jest documentation to troubleshoot an issue with a test. So far, I haven't been able to come up with a solution that actually works. The snapshot contains a defaultValue tha ...

Enhance the CSS styling for the React-Calendly integration in a React project

I am trying to customize the CSS of an Inline Widget called React Calendly. I have attempted to use React Styled Component Wrapper, Frame React Component, and DOM javascript but unfortunately, the design changes are not reflecting as desired. Specifically, ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...