Harnessing the power of JavaScript functions to display an image when clicked

Looking for help with making an image appear when clicking on one of three images? Despite trying different approaches, the desired result is still not achieved. I'm aware of using if else statements but exploring other methods. Any insights on what might be missing or incorrect would be greatly appreciated.

         var figElement = document.getElementById("placeholder");  
    var imgSource = document.getElementById("image");  
    var figCap = document.querySelector("figcaption");
    
    //display first picture
    function pic1() {
        imgSource.src = "images/trunk-bay.jpg";
        imgSource.alt = "Elevated view of Trunk Bay beach on St. John";
        figElement.style.display = "block"; 
        figCap.textContent = "Trunk Bay in St. John";
    }
    
    //display second picture
    function pic2() {
        imgSource.src = "images/sanjuan.jpg";
        imgSource.alt = "Elevated view of Elevated view of San Juan coast";
        figElement.style.display = "block";
        figCap.textContent = "Coast of San Juan";
    }
    
    //display third picture
    function pic3() {
        imgSource.src = "images/curacao.jpg";
        imgSource.alt = "The blue waters of Curacao";
        figElement.style.display = "block";
        figCap.textContent = "Curacao"; 
    }
<!DOCTYPE html>

<html lang="en">
<head>
    <title></title>
    <meta charset="utf-8>
  <link rel='stylesheet' href="css/styles.css">
</head>
<script src="scripts/script.js"></script>
<body>

    <div id="container">

        <header>
            <h1>Visit the Caribbean</h1>
        </header>

        <nav>
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="#">Places</a></li>
                <li><a href="#">Gallery</a></li>
                <li><a href="#">Contact</a></li>
            </ul>
        </nav>

        <main>

           <p>Discover the beauty of the Caribbean with its stunning islands and picturesque beaches. Click on the images below to see more.</p>

            <figure>

                <img src="images/trunk-bay-thumb.jpg" alt="Elevated view of Trunk Bay beach on St. John" onclick='pic1()'>
                <img src="images/sanjuan-thumb.jpg" alt="Elevated view of San Juan coast" onclick='pic2()'>
                <img src="images/curacao-thumb.jpg" alt="The blue waters of Curacao" onclick='pic3()'>

           </figure>
            
            <figure id="placeholder">
            
                <img src="image" alt="placeholder" id="image">
                <figcaption></figcaption>
            
            </figure>

        </main>

        <footer>
      
        </footer>
        
    </div>
    
</body>
</html>

   

Answer №1

It appears that your code is functioning correctly. Try moving your JavaScript script declaration tag to the end of the HTML body element and ensure that your image sources are in the correct place:

var figElement = document.getElementById("placeholder");  
    var imgSource = document.getElementById("image");  
    var figCap = document.querySelector("figcaption");
    
    //Function to display the first picture
    function pic1() {
        imgSource.src = "https://picsum.photos/50/50";
        imgSource.alt = "Elevated view of Trunk Bay beach on St. John";
        figElement.style.display = "block"; 
        figCap.textContent = "Trunk Bay in St. John";
    }
    
    //Function to display the second picture
    function pic2() {
        imgSource.src = "https://picsum.photos/75/75";
        imgSource.alt = "Elevated view of San Juan coast";
        figElement.style.display = "block";
        figCap.textContent = "Coast of San Juan";
    }
    
    //Function to display the third picture
    function pic3() {
        imgSource.src = "https://picsum.photos/100/100";
        imgSource.alt = "The blue waters of Curacao";
        figElement.style.display = "block";
        figCap.textContent = "Curacao"; 
    }
<!DOCTYPE html>

<html lang="en">
<head>
    <title></title>
    <meta charset="utf-8">
  <link rel='stylesheet' href="css/styles.css">
</head>
<body>

    <div id="container">

        <header>
            <h1>Explore the Caribbean Islands</h1>
        </header>

        <nav>
            <ul>
                <li><a href="index.html">Home</a></li>
                <li><a href="#">Destinations</a></li>
                <li><a href="#">Gallery</a></li>
                <li><a href="#">Contact Us</a></li>
            </ul>
        </nav>

        <main>

           <p>Discover the beauty of the Caribbean with its stunning beaches, crystal-clear waters, and endless sunshine! Click on the images below for a closer look.</p>

            <figure>

                <img src="https://picsum.photos/50/50" alt="Elevated view of Trunk Bay beach on St. John" onclick='pic1()'>
                <img src="https://picsum.photos/75/75" alt="Elevated view of San Juan coast" onclick='pic2()'>
                <img src="https://picsum.photos/100/100" alt="The blue waters of Curacao" onclick='pic3()'>

           </figure>
            
            <figure id="placeholder">
            
                <img src="image" alt="placeholder" id="image">
                <figcaption></figcaption>
            
            </figure>

        </main>

        <footer>
      
        </footer>
        
    </div>
    
<script src="scripts/script.js"></script>
</body>
</html>

Answer №2

It appears that null values are being returned for figElement, imgSource, and figCap, resulting in the error message "Cannot set properties of null."

The elements you were trying to access were not present in the DOM at the time your script executed. Please refer to Why does jQuery or a DOM method such as getElementById not find the element? for more information.

To resolve this issue, consider moving your import statement before the closing body tag </body>.


To simplify your code, consider using a class (e.g., fig-img) for each image and attaching a click listener to it. This approach will make your code more adaptable when adding additional images without the need to create a separate function for each image click event. See the sample code below:

HTML

<figure>
  <img
    src="images/trunk-bay-thumb.jpg"
    alt="Elevated view of Trunk Bay beach on St. John"
    class="fig-img"
  />
  <img
    src="images/sanjuan-thumb.jpg"
    alt="Elevated view of San Juan coast"
    class="fig-img"
  />
  <img
    src="images/curacao-thumb.jpg"
    alt="The blue waters of Curacao"
    class="fig-img"
  />
</figure>

<figure id="placeholder">
  <img src="image" alt="placeholder" id="image" />
  <figcaption></figcaption>
</figure>

JS

var figElement = document.getElementById("placeholder");
var imgSource = document.getElementById("image");
var figCap = document.querySelector("figcaption");
var figImages = document.querySelectorAll(".fig-img");

figImages.forEach((f) => {
  f.addEventListener("click", ({ target: { src, alt } }) => {
    imgSource.src = src;
    imgSource.alt = alt;
    figElement.style.display = "block";
    figCap.textContent = alt;
  });
});

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

Is it possible for Websockets to receive data from Ajax requests?

I am currently working on creating a PHP and HTML5 websocket chat system. In this setup, one end will be a socket while the other end will be AJAX. Is it possible for PHP's socket_recv() function to receive data from sources like AJAX, MySQL, or any o ...

Are none of the page links clickable?

Currently, I am in the process of creating a portfolio website. This is my first attempt at coding HTML and CSS from scratch without the aid of a layout template. I've encountered an issue that has me stumped - the links within the container are not ...

I'm struggling to determine the source of the color for my linked CSS. Any ideas where to look?

I am experiencing an issue with a link that is displaying as white and gray for "a" and "a:hover", despite my CSS file specifying otherwise. Firebug confirms this, but I can't figure out what is overriding it. Can anyone offer any insight? Below is t ...

Import necessary styles into the shadow DOM

Embracing the concept of shadow dom styles encapsulation is exciting, but I wish to incorporate base styles into each shadow dom as well (reset, typography, etc). <head> <link rel="stylesheet" href="core.css"> ... </h ...

I'm looking to create a parent div that adjusts its size dynamically and can contain two child divs, each with variable sizes that can scroll independently. How can I achieve this?

Consider this layout configuration: <div id="PARENT_DIV"> <div id="LEFT_CHILD_DIV"> </div> <div id="RIGHT_CHILD_DIV"> </div> </div> Key features for PARENT_DIV: PARENT_DIV must have a higher z-ind ...

Is it possible to swap two classes with each other using jQuery?

I am trying to implement a tree view with the following code snippet. Within the tree view, there are spans that have either the CollOpen or CollClosed class assigned to them. How can I toggle between these two classes on click for each span? .tree ...

Issue with React Hot Toast not displaying properly due to being positioned behind the <dialog>

The Challenge of Toast Notifications Visibility with <dialog> Element tl;dr When utilizing the native dialog.showModal() function, the <dialog> element appears to consistently remain on top, which causes toast notifications to be obscured by ...

Aligning the navigation links vertically

I am working on aligning my navigation bar vertically, even when I scroll the page. I found a method in another thread which suggests using the following CSS code for vertical alignment: #container { position: absolute; top: 50%; height: 400p ...

Revamp the sequence of divs using jQuery

<div class="example first">111</div> <div class="example second">222</div> <div class="example third">333</div> Can the order of these divs be changed using jQuery? I am looking to get: <div class="example second"&g ...

A JSON object received from an AJAX request is either null or empty

I recently deleted a previous question that I had posted because it was no longer relevant and there was another issue to address. The response provided below is very clear, more so than other responses, and I believe it will be beneficial for anyone else ...

Obtaining a complex object from a Checkbox set in AngularJS through the use of ngModel

Hey there! I've been searching on Stack Overflow regarding this topic, but I haven't found a solution that matches exactly what I need. If you want to take a look at the code, here is a JSFiddle link for reference: http://jsfiddle.net/gsLXf/1/ ...

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

What is the best way to center these icons vertically in my navigation menu using CSS?

My website has a navigation menu with third-party icon libraries (Material/FontAwesome) in use. I am facing an issue where the icons are not aligning vertically with the anchor text. Adjusting the font size of the icon to match the text results in it appe ...

Which is better: using multiple makeStyles or just one in Material UI?

Uncertain about the best approach in this situation. Is it acceptable to generate styles using makeStyles for each component individually, or would it be better to create one in the base component and simply pass down class names? ...

Encountering difficulty when determining the total cost in the shopping cart

I am currently working on a basic shopping cart application and I am facing an issue when users add multiple quantities of the same product. The total is not being calculated correctly. Here is my current logic: Data structure for Products, product = { ...

Locate the initial ancestor element, excluding the parent element that comes before the root ancestor

My HTML structure is as follows: <div> <ul> <li> <div>Other elements</div> <div> <ul> <li class='base-parent parent'> <div>Base Parent ...

Utilizing Angular.js to extract data from a deeply nested array of objects in JSON

Hello, I am currently learning about Angular.js and working on developing a shopping cart. In this project, I need to display an image, name, and cost of each product for multiple tenants. Each tenant has an array called listOfBinaries which contains listO ...

When trying to authorize my channel, the JSON data is coming back as a blank string

I've encountered an issue with my JavaScript code: Pusher is throwing the error message "JSON returned from auth endpoint was invalid, yet status code was 200. Data was: ", indicating empty data. I have double-checked the broadcasting service provider ...

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

"Crafting a sleek card design using Material UI components in React JS

Exploring the world of material UI and looking to create a card with an image and footer. However, I'm facing challenges as there is no default option for adding a footer in the card. https://i.stack.imgur.com/xlxyb.png I want the image to be center ...