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

The Safari browser is having trouble rendering the website's CSS and HTML properly

Check out this example of how the website should look on Chrome for Android: https://i.stack.imgur.com/RzUSp.jpg And here is an example from Safari on iPad Mini 2: https://i.stack.imgur.com/PAj2i.jpg The Safari version doesn't display the proper fon ...

Maintain the active menu open when navigating to a different page on the website

My website has a dropdown menu, but whenever I click on a submenu link, the new page opens and the menu closes. However, I want the active menu to remain open on the new page of the website! To demonstrate what I have tried in a simple way, I created an e ...

Troubleshooting a mapping problem with CSS elements

While building my website, I have successfully mapped the elements by ID for all alphabet letters except A. When clicking on the letter A, it does not go to the respective elements. Can anyone please help me find a solution? Visit this link for reference ...

Leveraging dynamic anchor tags within a Chrome extension

In my current project, I am dynamically generating anchor tags and using them to redirect to another page based on their unique IDs. While I have successfully implemented this feature using inline scripts in the past, I ran into an issue with Chrome exte ...

Obtain the ending section of a URL using JavaScript

Is it possible to extract the username from a URL like this example? I'm interested in seeing a regex method for achieving this. The existing code snippet only retrieves the domain name: var url = $(location).attr('href'); alert(get_doma ...

At what point are DOMs erased from memory?

Recently, I've been working on an application that involves continuous creation and removal of DOM elements. One thing I noticed is that the process memory for the browser tab keeps increasing even though the javascript heap memory remains steady. To ...

What are the reasons for the failure of parsing this specific Twitter JSON file using Angular $http, and how can I troubleshoot and resolve the issue

After finding a JSON example on the following website (located at the bottom): , I decided to save it to a file on my local system and attempt to retrieve it using Angular's $http service as shown below: To begin, I created a service: Services.Twitt ...

The raycaster fails to detect collision with the .gltf model

When using the raycaster to detect mouse intersection with a cube, everything works perfectly: raycaster.setFromCamera(mouse, camera) const intersects = raycaster.intersectObject(cubeMesh) if(intersects.length > 0) console.log('intersecting ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

Retrieving data from a div container on an active website

Imagine having a website similar to , where you want to automatically retrieve the time value every second and save it in a .txt file. Initially, I considered using OCR (optical character recognition) software for this task, but soon realized that relying ...

The Req.session array is limited to storing just one element at a time

I'm currently working on integrating a shopping cart feature into my Express/MongoDB e-commerce app that sells sneakers. To add an item to the cart, I extract the quantity and size from req.body and the itemId from req.session (previously saved when l ...

How can I use CSS to conceal the controls for an HTML5 video?

Seeking advice on how to hide and show controls on an HTML5 video section. I currently have a setup where clicking on the video div opens a modal that plays the video in a larger size. The code for opening the modal and playing the video is working fine. ...

Is it possible to apply a click effect to a specific child element of a parent using jQuery?

Struggling to figure out how to modify this jQuery code so that only the parent of the clicked button displays its child. Currently, all children are displayed when any button is clicked, not just the one within the targeted parent. I attempted using $(t ...

What's the significance of & in TypeScript and JavaScript?

While exploring someone else's code, I came across this interesting piece related to the props of a React component. Although I'm aware that & is typically used as an AND logical operator, it seems to have a different significance in this con ...

Having difficulty removing new or existing lines on StackBlitz

I attempted to experiment with React on StackBlitz, but I encountered a problem where I couldn't delete any lines of code. It seems that while I can add new lines of code, deleting them is not an option. Even when logging in with GitHub, the issue per ...

Nested Angular click events triggering within each other

In my page layout, I have set up the following configuration. https://i.stack.imgur.com/t7Mx4.png When I select the main box of a division, it becomes highlighted, and the related department and teams are updated in the tabs on the right. However, I also ...

Can you retrieve the second value using JSON.stringify?

Currently implementing JSON.stringify(data.message) which returns the following value: [ { "code":"PasswordTooShort", "description":"Passwords must be at least 6 characters." } ] I aim to extract the description value for my alert message ...

Encountering an unexplained JSON error while working with JavaScript

I'm trying to retrieve data from a JSON API server using JavaScript AJAX and display it in an HTML table. However, I keep encountering an undefined error with the data displaying like this: Name id undefined undefined This is my code snippe ...

Stop Bootstrap 5 Accordion from collapsing

I have successfully implemented the Accordion component in Bootstrap 5, and it is working perfectly! However, I am facing an issue with the size of the collapse button in the accordion, which is too big. I want to add an additional link to it for some ext ...

File download is initiated through an Ajax response

Utilizing Polymer's iron-ajax element, I am making an XMLHTTPRequest to a server endpoint: <iron-ajax id="ajax" method="POST" url="/export/" params='' handle-as="json" on-response="handleResponse" </iron-ajax> The resp ...