Go Back Home

How to Write Your Own ChatGPT with JavaScript, CSS, and HTML

The way we communicate with automated chatbots has drastically changed in the last few months or years thanks to ChatGPT. You might be interested in developing your own ChatGPT if you're a novice web developer. The good news is that a ChatGPT clone can be made with HTML, CSS, and plain JavaScript.

If you're not familiar, OpenAI developed ChatGPT, a sophisticated chatbot model. It generates human-like responses in a conversational format using artificial intelligence. Due to its capacity to mimic real interactions, ChatGPT has become extremely popular.

I will walk you through the process of making your very own ChatGPT using HTML, CSS, and JavaScript in this blog article. By constructing a ChatGPT

ChatGPT Clone HTML & JavaScript Video Tutorial

The offered video is a great resource for you to learn how to create your own ChatGPT if you learn best through video lessons. I break down each line of code in the video and include helpful comments to make it understandable for beginners.

You can read this post if you like to read blogs or if you just want a short rundown of the procedures for making a ChatGPT clone project. You'll have your own ChatGPT that you can chat with by the end of this article.

How to Create a JavaScript & HTML ChatGPT Clone

  1. Establish a folder. You can give this folder any name you like, and then create the aforementioned files inside of it.
  2. Make a file called index.html. The file must have the name index and the .html extension.
  3. style.css should be created. Style and its extension must be in the file name .css.
  4. Make a file called script.js. The file name and extension must both be script.js.
  5. Place the pictures folder in your project directory after downloading it. The chatbot logo and user avatar are both contained in this folder.

Add the following HTML codes to your index.html file to get started:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChatGPT Clone</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="chat-container">
        <!-- Chat messages will be added here dynamically with JavaScript -->
    </div>
    <div class="user-input">
        <input type="text" id="user-message" placeholder="Type your message...">
        <button id="send-button">Send</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

You will discover an empty "chat-container" div in this chunk of code. We will later use JavaScript to dynamically add the “chat” div that will contain all the chat details.

Send
light_mode delete
            <!DOCTYPE html>
            <html lang="en" dir="ltr">
            <head>
                <meta charset="utf-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>ChatGPT Clone in JavaScript | WilsonWanjiru</title>
                <link rel="stylesheet" href="style.css">
                <!-- Google Fonts Link For Icons -->
                <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Rounded:wght@100..700">
            </head>
            <body>
                <!-- Chats Container -->
                <div class="chat-container">
                    <!-- Typing container -->
                    <div class="typing-container">
                        <div class="typing-content">
                            <div class="typing-textarea">
                                <textarea id="chat-input" spellcheck="false" placeholder="Enter a prompt here" required></textarea>
                                <span id="send-btn" class="material-symbols-rounded">Send</span>
                            </div>
                            <div class="typing-controls">
                                <span id="theme-btn" class="material-symbols-rounded">light_mode</span>
                                <span id="delete-btn" class="material-symbols-rounded">delete</span>
                            </div>
                        </div>
                    </div>
                </div>
            </body>
            </html>
        

Then, include the subsequent CSS codes in your style. Apply visual decoration to your ChatGPT interface using a CSS file.

The web page will now load in your browser and show ChatGPT with a text input area and a few icons at the bottom.

CSS Code


    

    

Add the following JavaScript code to your script.js file to complete the process. By activating functions like chat, switching between dark and light themes, and saving conversation history in the browser, this script code will make your ChatGPT functional.

const chatInput = document.querySelector("#chat-input");
            const sendButton = document.querySelector("#send-btn");
            const chatContainer = document.querySelector(".chat-container");
            const themeButton = document.querySelector("#theme-btn");
            const deleteButton = document.querySelector("#delete-btn");
            let userText = null;
            const API_KEY = "PASTE-YOUR-API-KEY-HERE"; // Paste your API key here
            const loadDataFromLocalstorage = () => {
                // Load saved chats and theme from local storage and apply/add on the page
                const themeColor = localStorage.getItem("themeColor");
                document.body.classList.toggle("light-mode", themeColor === "light_mode");
                themeButton.innerText = document.body.classList.contains("light-mode") ? "dark_mode" : "light_mode";
                const defaultText = `

ChatGPT Clone

Start a conversation and explore the power of AI.
Your chat history will be displayed here.

` chatContainer.innerHTML = localStorage.getItem("all-chats") || defaultText; chatContainer.scrollTo(0, chatContainer.scrollHeight); // Scroll to bottom of the chat container } const createChatElement = (content, className) => { // Create new div and apply chat, specified class and set html content of div const chatDiv = document.createElement("div"); chatDiv.classList.add("chat", className); chatDiv.innerHTML = content; return chatDiv; // Return the created chat div } const getChatResponse = async (incomingChatDiv) => { const API_URL = "https://api.openai.com/v1/completions"; const pElement = document.createElement("p"); // Define the properties and data for the API request const requestOptions = { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ model: "text-davinci-003", prompt: userText, max_tokens: 2048, temperature: 0.2, n: 1, stop: null }) } // Send POST request to API, get response and set the reponse as paragraph element text try { const response = await (await fetch(API_URL, requestOptions)).json(); pElement.textContent = response.choices[0].text.trim(); } catch (error) { // Add error class to the paragraph element and set error text pElement.classList.add("error"); pElement.textContent = "Oops! Something went wrong while retrieving the response. Please try again."; } // Remove the typing animation, append the paragraph element and save the chats to local storage incomingChatDiv.querySelector(".typing-animation").remove(); incomingChatDiv.querySelector(".chat-details").appendChild(pElement); localStorage.setItem("all-chats", chatContainer.innerHTML); chatContainer.scrollTo(0, chatContainer.scrollHeight); } const copyResponse = (copyBtn) => { // Copy the text content of the response to the clipboard const reponseTextElement = copyBtn.parentElement.querySelector("p"); navigator.clipboard.writeText(reponseTextElement.textContent); copyBtn.textContent = "done"; setTimeout(() => copyBtn.textContent = "content_copy", 1000); } const showTypingAnimation = () => { // Display the typing animation and call the getChatResponse function const html = `
chatbot-img
content_copy
`; // Create an incoming chat div with typing animation and append it to chat container const incomingChatDiv = createChatElement(html, "incoming"); chatContainer.appendChild(incomingChatDiv); chatContainer.scrollTo(0, chatContainer.scrollHeight); getChatResponse(incomingChatDiv); } const handleOutgoingChat = () => { userText = chatInput.value.trim(); // Get chatInput value and remove extra spaces if(!userText) return; // If chatInput is empty return from here // Clear the input field and reset its height chatInput.value = ""; chatInput.style.height = `${initialInputHeight}px`; const html = `
user-img

${userText}

`; // Create an outgoing chat div with user's message and append it to chat container const outgoingChatDiv = createChatElement(html, "outgoing"); chatContainer.querySelector(".default-text")?.remove(); chatContainer.appendChild(outgoingChatDiv); chatContainer.scrollTo(0, chatContainer.scrollHeight); setTimeout(showTypingAnimation, 500); } deleteButton.addEventListener("click", () => { // Remove the chats from local storage and call loadDataFromLocalstorage function if(confirm("Are you sure you want to delete all the chats?")) { localStorage.removeItem("all-chats"); loadDataFromLocalstorage(); } }); themeButton.addEventListener("click", () => { // Toggle body's class for the theme mode and save the updated theme to the local storage document.body.classList.toggle("light-mode"); localStorage.setItem("themeColor", themeButton.innerText); themeButton.innerText = document.body.classList.contains("light-mode") ? "dark_mode" : "light_mode"; }); const initialInputHeight = chatInput.scrollHeight; chatInput.addEventListener("input", () => { // Adjust the height of the input field dynamically based on its content chatInput.style.height = `${initialInputHeight}px`; chatInput.style.height = `${chatInput.scrollHeight}px`; }); chatInput.addEventListener("keydown", (e) => { // If the Enter key is pressed without Shift and the window width is larger // than 800 pixels, handle the outgoing chat if (e.key === "Enter" && !e.shiftKey && window.innerWidth > 800) { e.preventDefault(); handleOutgoingChat(); } }); loadDataFromLocalstorage(); sendButton.addEventListener("click", handleOutgoingChat);

OpenAI API Key Instructions

Please keep in mind that your ChatGPT is not yet equipped to produce chats from prompts. You must pay close attention to a vital aspect of the code in order to make it work. You must paste an "OpenAI API key" into the API_KEY field, as you can see if you look more closely.

Visit https://platform.openai.com/account/api-keys to obtain your API key. You can create a free API key by logging into your account there after arriving.

To comprehend more aspects of the code, I suggest viewing the instructional video, going over the code comments, and playing around with the code.

Keep in mind that you'll receive a free $5 credit for your API usage when you sign up for OpenAI. When an account is more than three months old or the credit runs out, you’ll need a paid account or create a new one with a new number to keep using the API. Your API usage and expiration date can be found on the account’s usage page.

Final Thoughts and Conclusion

Congratulations! Using HTML, CSS, and plain JavaScript, you were able to effectively develop a ChatGPT clone project and incorporate the OpenAI API. You may now have deep discussions and show off your skills to friends and others. You can download the source code files for this ChatGPT clone project for free by clicking the Download button if you run into any problems while developing your own ChatGPT or if your code is not performing as planned.

Keep in mind that after downloading the file, you must insert an "OpenAI API key" into the script.js file's API_KEY variable. Visit the OpenAI API Keys page to acquire your API key.

If you'd like to get in touch or discuss potential collaboration opportunities, feel free to drop me an email at wilsonmuita41@gmail.com. I'm also active on LinkedIn and Facebook, where I share web development insights and updates.

Thank you for visiting my blog, and I hope you find it informative and inspiring. Let's connect and embark on this exciting journey together!