What is the best way to connect an HTML image to effortlessly switch between displaying and hiding an element (specifically, a table) using JavaScript?

Apologies if my question is a bit confusing and poorly written, as I am new to coding and Stack Overflow. What I am trying to achieve is the ability to click on each image and have a different table pop up for each planet with facts (an example of the Mercury table is shown in the picture). I already have the table set up where I want it to appear, but I'm not sure how to link it to each image and replace it with a different table associated with the selected planet (I hope this makes sense!).

I haven't written any JavaScript code yet, but I assume I'll need a separate function for each image?

Also, how can I add space (padding, I think?) between the HTML images?

So many questions, sorry about that! 😂

h1 {
  color: seagreen
}
h4 {
  color: seagreen
}
table {
font-family: Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 67%;
}
td {
border: 2px solid black;
text-align: left;
font-family: Arial, Helvetica, sans-serif;
padding: 1ex
}
th {
border: 3px solid black;
text-align: center;
font-family: Arial, Helvetica, sans-serif;
padding: 1ex
}
mercury {
  
}
<h1>The Eight Planets</h1>
<h4> Click on any planet below to learn!</h4>
<!-- mercury -->
<img id = "mercury"
src="https://img.purch.com/w/660/aHR0cDovL3d3dy5zcGFjZS5jb20vaW1hZ2VzL2kvMDAwLzAwMy8wOTcvb3JpZ2luYWwvaWcyOTVfcGxhbmV0c19NZXJjdXJ5XzAyLmpwZw=="
width="100" height="100">
<table>
<tr>
  <th> PLANET PROFILE</th>
  <th>QUICK FACTS</th>
  </tr>
  <td> Moons: 0 </td>
  <td> Your weight on Mercury would be 38% of your weight on Earth </td>
  </tr>
  <td> Diameter: 4,879km </td>
  <td> A day on the surface of Mercury lasts 176 Earth days </td>
  </tr>
<td> Orbit period: 88 days </td>
<td> Mercury has more craters and impact marks that any other planet </td>
</tr>
<td> Surface temperature: -173 to 427°C </td>
<td> After the Earth, Mercury is the second densest planet </td>
</tr>
<td> First record: 14th century BC </td>
<td> The orbit of Mercury is an ellipse rather than circular </td>
<!-- venus -->
<img id = "venus"
     src="https://s-media-cache-ak0.pinimg.com/originals/98/09/66/9809666c323d35c266117428dd495791.jpg" 
width="100" height="100">
<!-- earth -->
<img id = "earth" src="https://3c1703fe8d.site.internapcdn.net/newman/gfx/news/hires/2014/1-earth.jpg"
width="100" height="100">
<!-- mars --> 
<img id = "mars" src="https://upload.wikimedia.org/wikipedia/commons/0/02/OSIRIS_Mars_true_color.jpg"
width="100" height="100">
<!-- jupiter -->
<img id = "jupiter" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Jupiter_and_its_shrunken_Great_Red_Spot.jpg/330px-Jupiter_and_its_shrunken_Great_Red_Spot.jpg" width="100" height="100">
<!-- saturn --> 
<img id = "saturn" src="https://media.istockphoto.com/vectors/planet-saturn-vector-vector-id165060389?k=6&m=165060389&s=612x612&w=0&h=wfA9UIF6EaoGannx6fiE1gSe3G1ixtpGEfvXH2Eqhrg=" 
width="100" height="100">
<!-- uranus -->
<img id = "uranus" src="https://upload.wikimedia.org/wikipedia/commons/3/3d/Uranus2.jpg" 
width="100" height="100">
<!-- neptune -->
<img id = "neptune" src="https://img.purch.com/h/1000/aHR0cDovL3d3dy5zcGFjZS5jb20vaW1hZ2VzL2kvMDAwLzAwMC8xMjIvb3JpZ2luYWwvMDcwOTE4X25lcHR1bmVfMDIuanBn" 
width="100" height="100">
</html>

Answer â„–1

I made some slight modifications to the Id of your images, but essentially:

  • I included an array called arr_planets which holds the names of different planets.
  • By using JavaScript, I iterated through the arr_planets array and compared the id of the selected img with the values stored in the array.

The example below can serve as a reference for you:

// Array containing planet names.
var arr_planets = ["mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"];

/* Display the div based on the value of "id_planet_id" */
function showTable(id_planet_id) {
  // Iterate through the "arr_planets" array and compare with the parameter:
  for (var i = 0; i < arr_planets.length; i++) {
    // If matched, display it.
    if (arr_planets[i] == id_planet_id) {  
      document.getElementById(arr_planets[i]).removeAttribute("style");
    } else {
      // Otherwise, hide them.
      document.getElementById(arr_planets[i]).setAttribute("style", "display: none;");
    }
  }
}
h1 {
  color: seagreen
}

h4 {
  color: seagreen
}

table {
  font-family: Arial, Helvetica, sans-serif;
  border-collapse: collapse;
  width: 67%;
}

td {
  border: 2px solid black;
  text-align: left;
  font-family: Arial, Helvetica, sans-serif;
  padding: 1ex
}

th {
  border: 3px solid black;
  text-align: center;
  font-family: Arial, Helvetica, sans-serif;
  padding: 1ex
}

// Styling specific to mercury
mercury {}
<h1>The Eight Planets</h1>
<h4> Click on any planet below to learn!</h4>
<div id="divPlanets" class="divContAllPlanets">
  <!-- mercury -->
  <img id="mercury_img" src="https://img.purch.com/w/660/aHR0cDovL3d3dy5zcGFjZS5jb20vaW1hZ2VzL2kvMDAwLzAwMy8wOTcvb3JpZ2luYWwvaWcyOTVfcGxhbmV0c19NZXJjdXJ5XzAyLmpwZw==" width="100" height="100" onclick="showTable('mercury');" />
  <!-- venus -->
  <img id="venus_img" src="https://s-media-cache-ak0.pinimg.com/originals/98/09/66/9809666c323d35c266117428dd495791.jpg" width="100" height="100" onclick="showTable('venus');" />
  <!-- earth -->
  <img id="earth_img" src="https://3c1703fe8d.site.internapcdn.net/newman/gfx/news/hires/2014/1-earth.jpg" width="100" height="100" onclick="showTable('earth');" />
  <!-- mars -->
  <img id="mars_img" src="https://upload.wikimedia.org/wikipedia/commons/0/02/OSIRIS_Mars_true_color.jpg" width="100" height="100" onclick="showTable('mars');" />
  <!-- jupiter -->
  <img id="jupiter_img" src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Jupiter_and_its_shrunken_Great_Red_Spot.jpg/330px-Jupiter_and_its_shrunken_Great_Red_Spot.jpg" width="100" height="100" onclick="showTable('jupiter');" />
  <!-- saturn -->
  <img id="saturn_img" src="https://media.istockphoto.com/vectors/planet-saturn-vector-vector-id165060389?k=6&m=165060389&s=612x612&w=0&h=wfA9UIF6EaoGannx6fiE1gSe3G1ixtpGEfvXH2Eqhrg=" width="100" height="100" onclick="showTable('saturn');" />
  <!-- uranus -->
  <img id="uranus_img" src="https://upload.wikimedia.org/wikipedia/commons/3/3d/Uranus2.jpg" width="100" height="100" onclick="showTable('uranus');" />
  <!-- neptune -->
  <img id="neptune_img" src="https://img.purch.com/h/1000/aHR0cDovL3d3dy5zcGFjZS5jb20vaW1hZ2VzL2kvMDAwLzAwMC8xMjIvb3JpZ2luYWwvMDcwOTE4X25lcHR1bmVfMDIuanBn" width="100" height="100" onclick="showTable('neptune');" />
</div>
<div id="divTablesPlanets">
  <div id="mercury" style="display: none;">
    <i>Insert content for "mercury" table here.</i>
  </div>
  <div id="venus" style="display: none;">
    <i>Insert content for "venus" table here.</i>
  </div>
  <div id="earth" style="display: none;">
    <i>Insert content for "earth" table here.</i>
  </div>
  <div id="mars" style="display: none;">
    <i>Insert content for "mars" table here.</i>
  </div>
  <div id="jupiter" style="display: none;">
    <i>Insert content for "jupiter" table here.</i>
  </div>
  <div id="saturn" style="display: none;">
    <i>Insert content for "saturn" table here.</i>
  </div>
  <div id="uranus" style="display: none;">
    <i>Insert content for "uranus" table here.</i>
  </div>
  <div id="neptune" style="display: none;">
    <i>Insert content for "neptune" table here.</i>
  </div>
</div>

Answer â„–2

Simply copy and paste, I trust this will be beneficial - alter the planet specifics for every planet showcased on each planet's instance.

 <style>
            h1, h4 {
            color: seagreen
            }

            table {
            font-family: Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            width: 67%;
            }

            td {
            border: 2px solid black;
            text-align: left;
            font-family: Arial, Helvetica, sans-serif;
            padding: 1ex
            }

            th {
            border: 3px solid black;
            text-align: center;
            font-family: Arial, Helvetica, sans-serif;
            padding: 1ex
            }

            /*    spacing for your images*/
            img {
            margin: 10px 5px;
            }
            </style>
            <div align="center">
            <h1>The Eight Planets</h1>
            <!--    Enjoy this joke here, click to view-->
            <h4 onclick="myPlanet('wakanda');"> Click on any planet below for details!</h4>
            <!-- mercury -->
            <img onclick="myPlanet('mercury');"
            src="https://img.purch.com/w/660/aHR0cDovL3d3dy5zcGFjZS5jb20vaW1hZ2VzL2kvMDAwLzAwMy8wOTcvb3JpZ2luYWwvaWcyOTVfcGxhbmV0c19NZXJjdXJ5XzAyLmpwZw=="
            width="100" height="100">
            <!-- venus -->
            <img onclick="myPlanet('venus');"
            src="https://s-media-cache-ak0.pinimg.com/originals/98/09/66/9809666c323d35c266117428dd495791.jpg"
            width="100" height="100">
            <!-- earth -->
            <img onclick="myPlanet('earth');"
            src="https://3c1703fe8d.site.internapcdn.net/newman/gfx/news/hires/2014/1-earth.jpg"
            width="100" height="100">
            <!-- mars -->
            <img onclick="myPlanet('mars');"
            src="https://upload.wikimedia.org/wikipedia/commons/0/02/OSIRIS_Mars_true_color.jpg"
            width="100" height="100">
            <!-- jupiter -->
            <img onclick="myPlanet('jupiter');"
            src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/2b/Jupiter_and_its_shrunken_Great_Red_Spot.jpg/330px-Jupiter_and_its_shrunken_Great_Red_Spot.jpg"
            width="100" height="100">
            <!-- saturn -->
            <img onclick="myPlanet('saturn');"
            src="https://media.istockphoto.com/vectors/planet-saturn-vector-vector-id165060389?k=6&m=165060389&s=612x612&w=0&h=wfA9UIF6EaoGannx6fiE1gSe3G1ixtpGEfvXH2Eqhrg="
            width="100" height="100">
            <!-- uranus -->
            <img onclick="myPlanet('uranus');" src="https://upload.wikimedia.org/wikipedia/commons/3/3d/Uranus2.jpg"
            width="100" height="100">
            <!-- neptune -->
            <img onclick="myPlanet('neptune');"
            src="https://img.purch.com/h/1000/aHR0cDovL3d3dy5zcGFjZS5jb20vaW1hZ2VzL2kvMDAwLzAwMC8xMjIvb3JpZ2luYWwvMDcwOTE4X25lcHR1bmVfMDIuanBn"
            width="100" height="100">
            <table id="planetInfo">
            </table>
            </div>

            <script>
            //    Start with this and practice
            function myPlanet(planet) {
            var info = "";
            var planetInfo = document.getElementById("planetInfo");
                switch (planet) {
                    case "mercury":
                        info += "<tr><th> MERCURY PLANET PROFILE</th><th>QUICK FACTS</th></tr>";
                        info += "<tr><td> Moons: 0 </td><td> Your weight on Mercury would be 38% of your weight on Earth</td></tr>";
                        info += "<tr><td> Diameter: 4,879km </td><td> A day on Mercury lasts 176 Earth days </td></tr>";
                        break;
                        // Continue similar format for other planets

                 planetInfo.innerHTML = info;


                }


             </script>

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

The use of refs on Function components in SVG is not supported. Any attempts to access the ref will result in an

I am currently working on integrating a navigation bar component using an SVG image in Next.js. While attempting to import and utilize the SVG image, I encountered an error that I couldn't resolve. I tried using Emotion JS to create and use the SVG, ...

Identifying when an element hovers over a particular section

I am facing an issue with the side dot navigation on my website. The navigation is standard with a fixed position, but I also have two types of sections with different backgrounds - one white and the other black. The problem arises when the dots are not vi ...

Closing out with page content wrap-up

I am currently working on a personal project using Django for the back-end and Bootstrap for the front-end. I have encountered an issue where my footer is covering part of the content below "Diadema" in the list, and a scroll bar does not appear as it shou ...

What is the best way to access the iframe element?

This is main.html <body> <iframe id="frame" src="frame.html"></iframe> <script type="text/javascript"> document.getElementById('frame').contentWindow.document.getElementById('test').innerHtml = &apos ...

Create a duplicate of a div using JavaScript and modify the IDs of the inner elements within

I have two static div tags with a select tag and a text box inside, each with different IDs. When I clone the tag, it duplicates the same div tag in the DOM. How can I change the inner elements' tags? Below is the code snippet: <div id="m ...

Navigation menu with submenus containing buttons

I attempted to incorporate a dropdown into my existing navigation bar, but unfortunately, the dropdown content disappeared after adding the necessary code. I am now at a loss on how to troubleshoot this issue and make the dropdown function properly. Despit ...

Puzzling array challenge. Lack of clarity in explanation

I am currently working on a series of JavaScript tests available at js-assessment One of the tasks states: it("you should be able to find all occurrences of an item in an array", function() { var result = answers.findAllOccurrences('abcdefab ...

Tips for recognizing the click, such as determining which specific button was pressed

Currently, I am utilizing Angular 6. On the customer list page, there are three buttons - "NEW", "EDIT", and "VIEW" - all of which render to one component. As a result, it is crucial for me to determine which specific button has been clicked in order to ...

Troubleshoot: Issues arising when loading DataTables using AJAX with MYSQL

For some reason, I'm receiving an invalid JSON response from this code. The objective is to showcase SQL data in a table with search and sort functionalities using https://datatables.net/. Can you pinpoint where the issue might lie? GET.PHP $mysqli ...

Creating an element in jQuery without the need for a closing tag

My situation requires dynamically building HTML elements using jQuery. Firstly, I initiate the process with the following function: function createSection(divName) { $("#"+ divName).append("<section id='team' class='pb-5'>&b ...

When using nextjs, there is an issue that arises when attempting to define the property 'id' using context.params.id. This results in

Attempting to retrieve data from a JSON file (response.json) hosted on localhost:8000/response.json. Below is the code snippet from pages/test.js: import React from "react"; import Link from "next/link"; import Image from "next/ima ...

Tips for sending a command to the server using the ssh2-promise package in Node.js

In my current code, I am utilizing an SSH library to establish a connection to a server, create a shell session, and send a password to authenticate. However, I am encountering an issue where the password is not being sent as intended. Upon some debugging ...

Leverage Hubspot and Google Analytics to transfer session source and medium data

Is there a way to track session source and medium information in HubSpot to identify where a specific visit originated from before a form is filled out or another conversion event occurs? Ideally, this process would involve transferring the session and me ...

Issue with Plesk Obsidian, IISNode, and Express - application functioning solely in local environment

After setting up my Node.JS + Express.JS application on my server with IISNode and Plesk Obsidian, browsing the page in a browser triggers an error: I have already verified the permissions of the relevant folders and ensured that the "App Identities" have ...

Is there a way to programmatically click on a link within the first [td] element based on the status of the last [td] element in the same [tr] using codeceptjs/javascript?

The anticipated outcome: Pick a random assignment from the table that has the status "Not start". Below is the table provided: <table id="table1"> <tbody> <tr class="odd1"> <td> < ...

Is the definition of uniforms present in the THREE.js RawShaderMaterial?

The suggested reading regarding THREE.Js RawShaderMaterial states: Default uniforms and attributes are not automatically included in the GLSL shader code. Nevertheless, I have successfully executed the following shader using a rawShaderMaterial: ...

The function putImageData does not have the capability to render images on the canvas

After breaking down the tileset The tiles still refuse to appear on the <canvas>, although I can see that they are stored in the tileData[] array because it outputs ImageData in the console.log(tileData[1]). $(document).ready(function () { var til ...

Leverage a single property from a CSS class within another CSS class

I am facing an issue where I need to utilize one property from a CSS class in another CSS class. .class_a {margin:10px; width: 360px; float: left; color:#ffffff; ...etc...} .class_b { use the margin property of .class_a } Only utilize the margin propert ...

What is the process for deselecting a checkbox?

I am facing a situation where I need to uncheck a checkbox that is always checked based on user input from another section of my form. Specifically, I have implemented an onChange="functionName" event on a select box. Can someone guide me on how to accom ...

event videojs termination malfunction

I am trying to set up an event that triggers when my video finishes playing. I have placed the script right below my video tag. <script type="text/javascript> var myPlayer = videojs("session_video"); videojs("session_video").r ...