Skip to content
The Chat Archive
o1-mini-2024-09-12· OpenAI WildChat-4.8M (AI2)

Hello, please make me a script in html css and javascript that I can press the pick…

  1. User

    Hello, please make me a script in html css and javascript that I can press the pick button and it will give me a random pokemon card with the art and everything. Get the cards from a pokemon api or something, and make sure it is not just the name of the pokemon it is the actual pokemon card and art. Like pokesim.com. Go! In one file.

  2. Assistant

    Sure! Below is a complete HTML file that includes CSS and JavaScript to create a "Pick a Pokémon Card" button. When clicked, it fetches a random Pokémon Trading Card Game (TCG) card from the Pokémon TCG API and displays the card image along with some details.

    Steps to Use:

    1. Save the Code: Copy the code below into a file and save it with a .html extension, for example, pokemon_card_picker.html.
    2. Open in Browser: Open the saved file in any modern web browser.
    3. Pick a Card: Click the "Pick a Pokémon Card" button to fetch and display a random Pokémon card.

    Complete Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Random Pokémon Card Picker</title>
        <style>
            body {
                font-family: Arial, sans-serif;
                background-color: #f5f5f5;
                text-align: center;
                padding: 50px;
            }
    
            #pickButton {
                background-color: #ffcb05;
                border: none;
                color: #2a75bb;
                padding: 15px 32px;
                text-align: center;
                text-decoration: none;
                display: inline-block;
                font-size: 18px;
                margin-bottom: 30px;
                cursor: pointer;
                border-radius: 8px;
                transition: background-color 0.3s;
            }
    
            #pickButton:hover {
                background-color: #f2b807;
            }
    
            #cardContainer {
                display: none;
                margin-top: 20px;
            }
    
            #cardImage {
                width: 300px;
                height: auto;
                box-shadow: 0 4px 8px rgba(0,0,0,0.2);
                border-radius: 10px;
            }
    
            .card-details {
                margin-top: 15px;
                font-size: 18px;
                color: #333;
            }
    
            .loading {
                font-size: 20px;
                color: #555;
            }
    
            .error {
                font-size: 20px;
                color: red;
            }
        </style>
    </head>
    <body>
    
        <h1>Random Pokémon Card Picker</h1>
        <button id="pickButton">Pick a Pokémon Card</button>
    
        <div id="cardContainer">
            <img id="cardImage" src="" alt="Pokémon Card">
            <div class="card-details" id="cardDetails"></div>
        </div>
    
        <div id="statusMessage"></div>
    
        <script>
            const pickButton = document.getElementById('pickButton');
            const cardContainer = document.getElementById('cardContainer');
            const cardImage = document.getElementById('cardImage');
            const cardDetails = document.getElementById('cardDetails');
            const statusMessage = document.getElementById('statusMessage');
    
            // Function to fetch a random card
            async function fetchRandomCard() {
                try {
                    statusMessage.textContent = "Loading...";
                    statusMessage.className = "loading";
                    cardContainer.style.display = "none";
    
                    // First, get the total number of cards
                    const totalResponse = await fetch('https://api.pokemontcg.io/v2/cards?pageSize=1');
                    const totalData = await totalResponse.json();
                    const totalCards = totalData.totalCount;
    
                    // Generate a random page number
                    const pageSize = 250; // Maximum allowed by API
                    const totalPages = Math.ceil(totalCards / pageSize);
                    const randomPage = Math.floor(Math.random() * totalPages) + 1;
    
                    // Fetch a random page
                    const cardsResponse = await fetch(`https://api.pokemontcg.io/v2/cards?page=${randomPage}&pageSize=${pageSize}`);
                    const cardsData = await cardsResponse.json();
                    const cards = cardsData.data;
    
                    if (cards.length === 0) throw new Error("No cards found.");
    
                    // Select a random card from the page
                    const randomIndex = Math.floor(Math.random() * cards.length);
                    const randomCard = cards[randomIndex];
    
                    // Update the UI with card details
                    cardImage.src = randomCard.images.large || randomCard.images.small;
                    cardImage.alt = randomCard.name;
                    cardDetails.innerHTML = `
                        <strong>Name:</strong> ${randomCard.name} <br>
                        <strong>Set:</strong> ${randomCard.set.name} <br>
                        <strong>Rarity:</strong> ${randomCard.rarity || 'N/A'} <br>
                        <strong>Types:</strong> ${randomCard.types ? randomCard.types.join(', ') : 'N/A'}
                    `;
                    cardContainer.style.display = "block";
                    statusMessage.textContent = "";
                } catch (error) {
                    console.error(error);
                    statusMessage.textContent = "Failed to load card. Please try again.";
                    statusMessage.className = "error";
                }
            }
    
            pickButton.addEventListener('click', fetchRandomCard);
        </script>
    
    </body>
    </html>
    

    Explanation of the Code:

    1. HTML Structure:

      • Header (<h1>): Displays the title of the page.
      • Button (<button id="pickButton">): When clicked, triggers the function to fetch a random card.
      • Card Container (<div id="cardContainer">): Holds the card image and its details. Initially hidden.
      • Status Message (<div id="statusMessage">): Shows loading or error messages.
    2. CSS Styling:

      • Layout: Centers content and adds padding.
      • Button Styling: Styled with colors, padding, border-radius, and hover effects.
      • Card Styling: Sets width, shadow, and border-radius for the card image. Styles for details, loading, and error messages.
    3. JavaScript Functionality:

      • Fetch Total Number of Cards: Makes an initial request to determine how many cards are available.
      • Calculate Random Page: Since the API paginates results, it calculates a random page number based on the total number of cards and page size.
      • Fetch Cards from Random Page: Retrieves a set of cards from the randomly selected page.
      • Select a Random Card: Chooses a random card from the fetched set.
      • Display Card Information: Updates the image source and details in the UI.
      • Error Handling: Displays an error message if the fetch fails.
    4. API Usage:

      • Pokémon TCG API: The script uses the Pokémon TCG API v2 to fetch card data. No API key is required for low-volume requests, which is suitable for this application.

    Notes:

    • CORS Issues: The Pokémon TCG API supports CORS, so this script should work directly in the browser without any issues.
    • API Rate Limits: For extensive use, consider signing up for an API key to adhere to rate limits and usage policies.
    • Customization: You can enhance the script by adding more card details, styling, or additional features like searching for specific types or sets.

    Feel free to customize and expand upon this script to better suit your needs!