DEV Community

Sivakumar Mathiyalagan
Sivakumar Mathiyalagan

Posted on

Product page - fetch Api

SOURCE CODE :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Products</title>
<style>
    body{
        background-color: #f9f9f9;
       display: grid;
       grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
       padding :20px;
       font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
       gap: 20px;
}

div{
    background: white;
    border: 1px solid #ddd;
    border-radius: 10px;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    box-shadow: 0 4px 6px rgba(0,0,0,0.05);
}

h2{
    font-size: 1rem;
    height: 3em; 
    overflow: hidden;
    text-align: center;
    margin: 10px 0;
}

h3{
    color: #2c3e50;
    margin: 5px 0;
}

img{
    height: 150px; 
    width: auto;
    object-fit: contain; 
    margin-bottom: 15px;
}

 p {
    font-size: 0.85rem;
    color: #666;
    height: 4.5em; 
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3; 
    -webkit-box-orient: vertical;
}

</style>


</head>
<body>
    <script>
        // fetch('https://fakestoreapi.com/products')
        //     .then(res=>res.json())            
        //     .then(data=>console.log(data))


            async function products(){
                try{
                const res = await fetch('https://fakestoreapi.com/products');
                const data = await res.json();

               data.forEach(element => {
                const newDiv = document.createElement("div")
                const title = document.createElement("h2");
                const img = document.createElement("img");
                const price = document.createElement("h3");
                const rating = document.createElement("h3");
                const description = document.createElement("p");

                title.innerText = element.title;
                img.src = element.image;
                price.innerText = `PRICE   $${element.price}`;
                rating.innerText = `RATING   ${element.rating.rate}`;
                description.innerText = `Product Description   ${element.description}`


                newDiv.appendChild(title);
                newDiv.appendChild(img);
                newDiv.appendChild(price);
                newDiv.appendChild(rating);
                newDiv.appendChild(description);
                document.body.appendChild(newDiv);

               });

                }
                catch(err){
                    console.log(err)
                }
            }

            products();
    </script>


</body>
</html>
Enter fullscreen mode Exit fullscreen mode

OUTPUT :

link : https://products-api-ec8f9f.gitlab.io/product.html

Top comments (0)