Content
Code block
A code block with colours, a language label and a copy button. Plus a copy button for any text.
Code block
// add an item to the cart
function add(cart, item) {
const total = cart.total + item.price * 1.2;
return { ...cart, items: [...cart.items, item], total };
}
HTML
<pre data-pw-code data-lang="js" data-title="cart.js" data-lines><code>// add an item to the cart
function add(cart, item) {
const total = cart.total + item.price * 1.2;
return { ...cart, items: [...cart.items, item], total };
}</code></pre>Copy button for any text
HTML
<input class="pw-input" id="demo-key" value="pk_live_2f9a71c0" readonly style="max-width:220px" aria-label="API key">
<button class="pw-btn" data-pw-copy="#demo-key">Copy</button>
<button class="pw-btn" data-pw-copy data-text="https://example.com/invite/7Q2M" data-copied="Link copied">Copy the invite link</button>How to use it
Write HTML inside a code block with < and > instead of < and >, as in any web page.
Options
Set them as attributes on the element.
| Attribute | Default | What it does |
|---|---|---|
data-lang | Language for the colours and the label: html, css, js, json, bash, python, sql, php and other C-like languages. | |
data-title | Text in the header instead of the language, for example a file name. | |
data-lines | Line numbers. | |
data-copy | true | false removes the copy button. |
data-pw-copy | On any button: the selector of the element whose text or value is copied. Or use data-text. | |
data-copied | Copied | Text of the button for a moment after copying. |
Events
Listen with addEventListener. Details are in event.detail.
| Event | When |
|---|---|
pw:copy | On the button, with text. |
From your script
Partwise.copy('some text').then(function () { });
var html = Partwise.highlight('const a = 1;', 'js'); // safe HTML with <span> coloursGood to know
- The colouring is a small built-in one. It marks comments, strings, numbers, keywords and tags. It is not a full parser like the big highlighting libraries.
- Everything in the code is escaped, so code from people cannot run in your page.
- The block can be scrolled with the keyboard when lines are long.
- Copying needs a secure page (https or localhost) in most browsers. On other pages an older method is tried.
Files
Everything is in dist/partwise.css and dist/partwise.js. To load only this component, use src/css/00-base.css and src/js/00-core.js plus: css/40-code-tour.css, js/40-code.js.