Search Here

Create an HTML structure for the card and include a container where you’ll render the data



INDEX.HTML

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Sample API Data</title>

    <link rel="stylesheet" href="style.css">

</head>

<body>

    <div class="container">

        <!-- Data will be rendered here -->

    </div>


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

</body>

</html>


STYLE.CSS

.container {

    display: flex;

    flex-wrap: wrap;

    justify-content: center;

    gap: 20px;

}


.card {

    border: 1px solid #ddd;

    border-radius: 5px;

    padding: 20px;

    width: 300px;

    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);

    background-color: #fff;

}


.card h2 {

    font-size: 20px;

    margin: 0;

}


.card p {

    margin: 10px 0;

}


JAVASCRIPT.JS

// Function to fetch data from the API

async function fetchData() {

    try {

        const response = await fetch('https://jsonplaceholder.typicode.com/posts');

        const data = await response.json();

        return data;

    } catch (error) {

        console.error('Error fetching data:', error);

    }

}


// Function to render data in cards

async function renderData() {

    const container = document.querySelector('.container');

    const data = await fetchData();


    if (!data) {

        return;

    }


    data.forEach(item => {

        const card = document.createElement('div');

        card.classList.add('card');


        const title = document.createElement('h2');

        title.textContent = item.title;


        const body = document.createElement('p');

        body.textContent = item.body;


        card.appendChild(title);

        card.appendChild(body);

        container.appendChild(card);

    });

}


// Call the renderData function to display data

renderData();

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.