AI Code Explainer UI with HTML, CSS & JavaScript
40 DAYS 40 PROJECT CHALLENGE
Day #14
Project Overview
The AI Code Explainer is an interactive project built using HTML, CSS, and JavaScript. It allows users to paste code into a text area and request a simple explanation of what the code does. This project connects to an external AI API to generate the explanation. Users can paste their code into the input area and then JavaScript validates the input and displays an “Analyzing code…” message while the API request is being processed. It then sends the entered code to the OpenRouter Chat Completions API along with an instruction to explain the code in simple terms.
After receiving the API response, the generated explanation is displayed dynamically inside the output section. The interface uses a clean white card, dark blue background, large code input area, and a separate explanation box.
Key Features
- Code Input Area: Users can paste their source code into a large textarea and the
codeInputelement provides the main input area for the application. - Explain Code Button: The button calls the
explainCode()function when clicked. This starts the code analysis and API request process. - Empty Input Validation: Before making an API request, JavaScript checks whether the entered code contains any meaningful content. If the field is empty, the application displays a message asking the user to paste some code.
- Analyzing Status: While waiting for the API response, the output area displays “Analyzing code…”. This gives the user feedback that the request is being processed.
- External AI API Integration: The JavaScript uses the
fetch()API to send the user’s code to the OpenRouter Chat Completions endpoint. - AI Model Request: The request specifies
openai/gpt-3.5-turboas the model and sends the user’s code with the instruction to explain it in simple terms. - Asynchronous Processing: The
explainCode()function is declared withasync, whileawaitis used to wait for the API response and convert it into JSON. - Clean Explanation Area: The
#outputelement has its own light background, padding, rounded corners, and minimum height, creating a separate area for the generated explanation. - Simple User Interface: The application uses a centered white container, dark blue page background, rounded corners, and a blue action button to create a straightforward code-explanation interface.
- API Key Exposure: The current implementation places the OpenRouter API key directly inside browser-side JavaScript. This is functional for the provided code but is not secure for production, because users can inspect frontend source code and retrieve the key.
What You'll Learn
- How to retrieve textarea content using JavaScript.
- How to validate text using
trim(). - How to create asynchronous JavaScript functions with
async. - How to use
awaitwith asynchronous operations. - How to make API requests using the
fetch()method. - How to configure HTTP request methods and headers.
- How to send JSON data using
JSON.stringify(). - How to convert API responses into JavaScript objects using
response.json(). - How to use template literals to dynamically construct prompts.
- How to access nested properties from an API response.
- How to update webpage content dynamically using
innerText. - Why API keys should be protected instead of being exposed in frontend JavaScript.
HTML Code
The HTML creates the structure of the AI Code Explainer interface. The main application is contained inside the .container element, which includes the page heading, code input textarea, Explain Code button, explanation heading, and output area. The textarea uses the id="codeInput" attribute, allowing JavaScript to retrieve the code entered by the user. The button uses onclick="explainCode()" to call the asynchronous JavaScript function.
The <h2> element displays the Explanation heading, while the <div id="output"> initially contains the message “Your explanation will appear here…”. JavaScript later replaces this content with either a validation message, analyzing status, or the explanation returned by the API. The HTML also links the external style.css file for styling and script.js for the application logic.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>AI Code Explainer</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h1>AI Code Explainer</h1>
<textarea id="codeInput" placeholder="Paste your code here..."></textarea>
<button onclick="explainCode()">Explain Code</button>
<h2>Explanation</h2>
<div id="output">Your explanation will appear here...</div>
</div>
<script src="script.js"></script>
</body>
</html> CSS Code
The CSS starts with a universal reset that removes default margins and padding and applies box-sizing: border-box. Arial is used as the main font throughout the interface. The body selector creates the page layout using Flexbox. The dark blue #042354 background covers the viewport, while justify-content: center and align-items: center position the main container in the center.
The .container class creates the main white card with 30px padding, a 650px width, rounded corners, and a subtle box shadow, h2 selector adds a small margin around the Explanation heading and the textarea selector creates the code input area with full width, 200px height, padding, a light border, rounded corners, and bottom spacing.
This button selector creates a full-width blue button with white text, rounded corners, a pointer cursor, and bold font weight, button:hover selector changes the button’s background color when the user hovers over it. Finally, the #output selector styles the explanation area with a light background, padding, rounded corners, top spacing, and a minimum height. This provides a visually separate area for displaying the generated response.
*{
margin:0;
padding:0;
box-sizing:border-box;
font-family:Arial;
}
body{
background:#042354;
display:flex;
justify-content:center;
align-items:center;
height:100vh;
padding:20px;
}
h2{
margin: 5px !important;
}
.container{
background:white;
padding:30px;
border-radius:12px;
width:650px;
box-shadow:0 10px 30px rgba(0,0,0,0.1);
}
textarea{
width:100%;
height:200px;
padding:10px;
border:1px solid #ddd;
border-radius:6px;
margin-bottom:10px;
}
button{
width:100%;
padding:12px;
background:#2563eb;
border:none;
color:white;
border-radius:6px;
cursor:pointer;
font-weight:bold;
}
button:hover{
background:#1d4ed8;
}
#output{
background:#f1f5f9;
padding:15px;
border-radius:6px;
margin-top:10px;
min-height:100px;
} Javascript Code
The JavaScript functionality is contained inside the asynchronous explainCode() function. It first retrieves the code entered into the codeInput textarea and selects the output element where messages and explanations will be displayed. The function checks whether the entered code is empty by using code.trim(). If no code has been entered, it sets the output text to “Please paste some code.” and stops execution with return.
If code is available, the application changes the output to “Analyzing code…” before making the API request. The fetch() function then sends a POST request to the OpenRouter Chat Completions API. The request includes a Content-Type header and an authorization header containing the API key provided in the code. The request body is created with JSON.stringify() and contains the selected model along with a messages array. The user’s code is inserted into the prompt using a template literal, together with the instruction to explain the code in simple terms.
The await response.json() statement converts the API response into a JavaScript object. Finally, data.choices[0].message.content retrieves the generated explanation and assigns it to output.innerText, replacing the temporary analyzing message.
Security note: For a production application, the API request should be handled through a backend server. The API key should be stored in an environment variable on the server rather than exposed in frontend JavaScript.
async function explainCode(){
const code = document.getElementById("codeInput").value
const output = document.getElementById("output")
if(code.trim() === ""){
output.innerText = "Please paste some code."
return
}
output.innerText = "Analyzing code..."
const response = await fetch("https://openrouter.ai/api/v1/chat/completions", {
method:"POST",
headers:{
"Content-Type":"application/json",
"Authorization":"Bearer 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"
},
body:JSON.stringify({
model:"openai/gpt-3.5-turbo",
messages:[
{
role:"user",
content:`Explain this code in simple terms:\n\n${code}`
}
]
})
})
const data = await response.json()
output.innerText = data.choices[0].message.content
} Related Projects
Day 11 : AI Resume Skill Analyzer
Generates a user profile card dynamically from form inputs.
Concepts: Form handling, dynamic UI generation, data mapping.
Day 12 : AI Cover Letter Generator UI
Interactive comment/input system with real-time display updates.
Concepts: DOM manipulation, event handling, dynamic content updates.
Day 16 : AI Image Caption Generator
Generates captions for images based on user input or preview.
Concepts: File handling, dynamic text output, UI updates.