Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I display a random cat image from an API on my webpage using async-await in JavaScript and HTML?

I am writing a program which calls from an API to get a random cat image. I want to be able to display that image on my webpage and not just display the url in the console.

//This is my html (It is really basic but I just want to get the output to work)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Gif</title>
</head>

<body>
    <div class="container">
        <h1>This is a random image of a cat!</h1>
    </div>

    <script src="catGif.js">
    </script>
</body>

</html>

//This is my javascript

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

let container = document.querySelector(".container");
    async function apiFunction() {
        await fetch("https://api.thecatapi.com/v1/images/search")
            .then(res => res.json())
            .then((result) => {
                //items = result;
                let img = document.createElement("img");
                img.src = result[0].url;
                container.appendChild(img);

            }),
            (error) => {
                console.log(error);
            }
    }

>Solution :

You did not call your defined function.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cat Gif</title>
</head>

<body>
    <div class="container">
        <h1>This is a random image of a cat!</h1>
    </div>

    <script>
        let container = document.querySelector(".container");
        async function apiFunction() {
            await fetch("https://api.thecatapi.com/v1/images/search")
                .then(res => res.json())
                .then((result) => {
                    //items = result;
                    let img = document.createElement("img");
                    img.src = result[0].url;
                    container.appendChild(img);
                }),
                (error) => {
                    console.log(error);
                }
        }
        // Call the function
        apiFunction();
    </script>
</body>

</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading