HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<p class="help">
<i>**Will need to enable Chrome flags, Chrome canary recommended.</i>
</p>
<h2>Prompt AI API & Summarize AI API</h2>
<p>Output:</p>
<div id="output">
</div>
<div class="controls">
<input type="button" id ="prompt" value="1. Write a Poem" />
<input type="button" id ="summarize" value="2. Summarize" />
</div>
<details>
<summary>A made up Harry Potter excerpt</summary>
<p id="sample">
The Transfiguration classroom fell silent when Neville Longbottom's experimental spell went terribly wrong. What began as an attempt to transform his textbook into a singing teapot instead caused every piece of furniture in the room to sprout legs and begin a chaotic dance.
Desks waltzing with chairs, inkwells spinning like ballerinas, and quills doing a jig across Professor McGonagall's meticulously organized desk. The room became a whirling carnival of enchanted objects, with McGonagall's normally stern expression transforming into a mix of shock and barely contained exasperation.
Hermione, ever the problem-solver, began muttering counterspells while Harry and Ron ducked to avoid a particularly enthusiastic pirouetting table. Draco Malfoy, caught in the center of the madness, shrieked as a chair attempted to use him as a dancing partner.
"Finite Incantatem!" McGonagall finally bellowed, her voice cutting through the musical mayhem. The objects froze mid-twirl, then crashed to the ground with a spectacular cacophony of thuds and clatters.
Neville turned five shades of red, apologetic and mortified. "Sorry, Professor," he mumbled, as a lone teacup lid spun defiantly on the floor.</p>
</details>
<h2>Language Detetction API</h2>
<div class="language-translation">
<textarea id="input-text"></textarea>
<input type="button" id ="detect" value="3. Detect" />
<p>The Language detected is <span id="language">___</span> with Confidence <span id="confidence">___</span></p>
</div>
* {
font-family: Verdana;
}
.help {
color: #aaa;
}
#output {
background: antiquewhite;
border: 2px dashed #aaa;
border-radius: 8px;
padding: 20px;
}
.controls {
margin: 30px 0;
}
#language, #confidence {
font-weight: bold;
color: blueviolet;
}
#detect {
display: block;
}
(async () => {
// Define an asynchronous function to write a poem
const writePoem = async () => {
try {
// Check if the language model capabilities are available
const { available, defaultTemperature, defaultTopK, maxTopK } = await ai.languageModel.capabilities();
// console.log ((await ai.languageModel.capabilities()).available);
if (available !== "no") {
// Create a session for the language model
const session = await ai.languageModel.create();
// Prompt the model and wait for the result
document.getElementById("output").innerHTML = "Generating....";
const result = await session.prompt("Write me a poem");
if (result) {
// Display the result in the output element
document.getElementById("output").innerHTML = result;
} else {
console.log("No result received from the language model.");
}
} else {
console.log("Language model is not available.");
}
} catch (error) {
console.error("An error occurred:", error);
}
};
// Define an asynchronous function to summarize text
const summarize = async () => {
try {
// Check the summarizer's capabilities
const canSummarize = await ai.summarizer.capabilities();
let summarizer;
// Check if the summarizer is available
if (canSummarize && canSummarize.available !== 'no') {
if (canSummarize.available === 'readily') {
// If the summarizer is readily available, create an instance immediately
summarizer = await ai.summarizer.create();
} else {
// If the summarizer requires a model download, create an instance and track download progress
summarizer = await ai.summarizer.create();
// // Add an event listener to monitor download progress
// summarizer.addEventListener('downloadprogress', (e) => {
// console.log(`Download progress: ${e.loaded}/${e.total}`);
// });
// Wait for the summarizer to be ready after the download is complete
await summarizer.ready;
}
} else {
// Log a message if the summarizer is not available
console.log("The summarizer is not available for use.");
}
// Get the text to summarize
const someUserText = document.getElementById("sample").innerHTML;
document.getElementById("output").innerHTML = "Summarizing....";
const result = await summarizer.summarize(someUserText);
document.getElementById("output").innerHTML = result;
} catch (error) {
// Handle and log any errors that occur
console.error("An error occurred:", error);
}
};
const languageDetection = async () => {
try {
// Check the language detection capabilities
const canDetect = await translation.canDetect();
console.log("Language detection capability:", canDetect);
let detector;
if (canDetect === "no") {
// The language detector isn't usable.
console.log("Language detector is not available.");
return;
}
if (canDetect === "readily") {
// The language detector can immediately be used.
detector = await translation.createDetector();
// detector = new i18nextBrowserLanguageDetector();
console.log(detector);
} else {
// The language detector can be used after model download.
detector = await translation.createDetector();
detector.addEventListener("downloadprogress", (e) => {
console.log(`Download progress: ${e.loaded}/${e.total}`);
});
await detector.ready; // Ensure the detector is ready
}
// Retrieve user text safely
const userText = document.getElementById("input-text")?.value || "";
if (!userText.trim()) {
console.error("No input text found for detection.");
return;
}
console.log("Input text:", userText);
const detectionOutput = await detector.detect(userText);
console.log("Hello");
if (detectionOutput.length > 0) {
const { detectedLanguage, confidence } = detectionOutput[0];
document.getElementById("language").innerHTML = detectedLanguage;
document.getElementById("confidence").innerHTML = `${(confidence * 100).toFixed(1)}%`;
console.log("Detected Language:", detectedLanguage);
console.log("Confidence:", confidence);
} else {
console.warn("No language detected.");
}
console.log("Language detection completed.");
} catch (error) {
// Handle and log any errors that occur
console.error("An error occurred:", error);
}
};
// Global error handling
window.addEventListener('error', (event) => {
console.error('Global error caught:', event.error);
});
window.addEventListener('unhandledrejection', (event) => {
console.error('Unhandled promise rejection:', event.reason);
});
// Trigger function with additional error catching
try {
languageDetection().catch(promiseError => {
console.error('Promise-level error:', promiseError);
});
} catch (syncError) {
console.error('Synchronous error in function call:', syncError);
}
// Attach the click event listener to the prompt button
const promptButton = document.getElementById("prompt");
if (promptButton) {
promptButton.addEventListener("click", writePoem);
} else {
console.error("Prompt button element not found.");
}
// Attach the click event listener to the Summarize button
const summarizeButton = document.getElementById("summarize");
if (summarizeButton) {
summarizeButton.addEventListener("click", summarize);
} else {
console.error("summarize button element not found.");
}
// Attach the language detection API to click for detect button.
const detectButton = document.getElementById("detect");
// console.log(detectButton);
if (detectButton) {
detectButton.addEventListener("click", languageDetection);
} else {
console.error("language detetction element not found.");
}
})();
Also see: Tab Triggers