# Code Language Switcher

One example is available in two programming languages, with a matching copy action.

## Try it

Switch between JavaScript and Python, then copy the visible example.

## Interaction details

Both examples count completed items. Changing languages updates the displayed code and the text sent to the clipboard.

## Where to use it

Technical documentation that presents equivalent code in several languages.

## Implementation prompt

> Show the equivalent snippet for the selected language and copy only that snippet.

## Sources and credits

- [Stripe API example in Node.js](<https://docs.stripe.com/api/setup_attempts/list?lang=node>)
- [Stripe API example in Python](<https://docs.stripe.com/api/setup_attempts/list?lang=python>)

## Checking the behavior

Switch the local counting example between JavaScript and Python, then copy the visible snippet. The hosted URL retains the language choice and Back restores the previous snippet. If clipboard access is unavailable, the code opens selected for manual copying.

## Standalone HTML

Save the code below as an HTML file and open it in your browser. The example works offline.

```html
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Code Language Switcher · UI Motion Lab</title>
<style>:root{color-scheme:light;--paper:#f5f3ec;--ink:#262820;--line:#c7c6b7;--accent:#98402b}
*{box-sizing:border-box}body{margin:0;background:var(--paper);color:var(--ink);font:15px/1.55 Arial,'Apple SD Gothic Neo','Malgun Gothic',sans-serif;overflow-wrap:anywhere}
main{width:min(810px,calc(100% - 36px));margin:clamp(20px,5vh,58px) auto}
main h1{margin:0;font-size:clamp(28px,4.1vw,47px);font-weight:700;line-height:1.15;letter-spacing:-.065em}
main>p{color:#56594e;margin:8px 0 22px;line-height:1.55}.panel{padding:clamp(15px,2.7vw,28px);background:#fffdf6;border:1px solid var(--line);border-radius:2px}
button,select,input,textarea{font:inherit}button,select{min-height:40px}button{cursor:pointer}button:disabled{cursor:default;opacity:.45}
button,select{background:#faf9f0;color:inherit;border:1px solid #a6a798;border-radius:3px;padding:5px 12px}
:focus-visible{outline:3px solid #945030;outline-offset:3px}button:enabled:hover,select:hover{border-color:var(--ink)}
[hidden]{display:none!important}.lab-embedded [data-lab-shell]{display:none!important}.lab-embedded main{margin:clamp(12px,2vh,25px) auto}
figure,fieldset{margin:0}p:last-child{margin-bottom:0}fieldset{min-width:0}
@media(max-width:460px){main{width:calc(100% - 24px);margin:16px auto}main>p{font-size:13px;margin:5px 0 14px}main h1{font-size:26px}.panel{padding:13px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.01ms!important;transition-duration:.01ms!important;scroll-behavior:auto!important}}
.lab-reduce *,.lab-reduce *::before,.lab-reduce *::after{animation-duration:.01ms!important;transition-duration:.01ms!important;scroll-behavior:auto!important}
.panel{padding:0;background:#222924;color:#f1eddb;border-color:#2d362f;overflow:hidden}
.toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap;padding:10px 14px;background:#303a32;border-bottom:1px solid #576050}
.toolbar label{font-size:13px;color:#dedfd0}.toolbar select,.toolbar button{background:#fff9;border-color:#b4b7a3;color:#172019;font-size:13px;min-height:35px}.toolbar #copy{margin-left:auto;background:transparent;color:#fff9df;border-color:#76816e}
.editor{padding:clamp(13px,3vw,26px)}.filename{font:12px/1.4 monospace;color:#c1cbb5;margin-bottom:12px}pre{margin:0;overflow-x:auto;max-width:100%;padding-bottom:5px;tab-size:2}code{font:clamp(12px,1.7vw,16px)/1.9 ui-monospace,Consolas,monospace;white-space:pre}.syntax-string{color:#e7bd8b}.syntax-word{color:#b1d6c7}
.console{display:flex;align-items:baseline;gap:15px;padding:9px 16px;color:#eeefd8;background:#3b493a}.console span{font-size:12px}.console strong{font:italic 24px Georgia,serif}
#status{font-size:12px;margin:0;color:#d8dfcf}#status:not(:empty){padding:6px 16px}#manual{width:calc(100% - 24px);min-height:75px;margin:0 12px 10px}
</style>
<script>
const viewOptions=new URLSearchParams(location.search);
document.documentElement.classList.toggle('lab-embedded',viewOptions.get('embed')==='1');
document.documentElement.classList.toggle('lab-reduce',viewOptions.get('reduce')==='1');
</script>
</head>
<body class="lab-example">
<main><h1>Code Language Switcher</h1><p>Choose a language and copy its example for counting completed items.</p>
<section class="panel" aria-label="Completed items example">
 <div class="toolbar"><label for="language">Code language</label><select id="language"><option value="js">JavaScript</option><option value="py">Python</option></select><button id="copy" type="button">Copy code</button></div>
 <div class="editor"><div class="filename"></div><pre tabindex="0" aria-label="Code in the selected language"><code id="code"></code></pre></div>
 <div class="console"><span>Expected output</span><strong>2 items</strong></div>
 <p role="status" id="status"></p><textarea id="manual" hidden readonly aria-label="Code to copy manually"></textarea>
</section>
</main>
<script>

const snippets = {
  js: 'const orders = ["done", "open", "done"];\nconst finished = orders.filter(status => status === "done");\nconsole.log(finished.length);',
  py: 'orders = ["done", "open", "done"]\nfinished = [status for status in orders if status == "done"]\nprint(len(finished))'
};
const language = document.querySelector("#language");
const code = document.querySelector("#code");
const status = document.querySelector("#status");
const manual = document.querySelector("#manual");
let revision = 0;
function display() {
  revision++;
  code.replaceChildren();
  const sample=snippets[language.value];
  const token=/"[^"]*"|\b(?:const|for|in|if|print|console|filter|len)\b/g;
  let start=0;
  for(const match of sample.matchAll(token)){
    code.append(document.createTextNode(sample.slice(start,match.index)));
    const span=document.createElement('span');
    span.className=match[0].startsWith('"')?'syntax-string':'syntax-word';
    span.textContent=match[0];code.append(span);start=match.index+match[0].length;
  }
  code.append(document.createTextNode(sample.slice(start)));
  document.querySelector('.filename').textContent=language.value==='js'?'count-completed.js':'count_completed.py';
  manual.hidden = true;
  manual.value = "";
  status.textContent = "";
}
function restore() {
  const key = new URL(location.href).searchParams.get("lang");
  language.value = Object.hasOwn(snippets, key) ? key : "js";
  display();
}
language.addEventListener("change", () => {
  display();
  if (!/^https?:$/.test(location.protocol)) return;
  const url = new URL(location.href);
  url.searchParams.set("lang", language.value);
  history.pushState(null, "", url);
});
document.querySelector("#copy").addEventListener("click", async () => {
  const selected = code.textContent;
  const label = language.selectedOptions[0].text;
  const atClick = revision;
  try {
    await navigator.clipboard.writeText(selected);
    if (atClick === revision) status.textContent = label + " Code copied.";
  } catch {
    if (atClick !== revision) return;
    manual.hidden = false;
    manual.value = selected;
    manual.focus();
    manual.select();
    status.textContent = "Copy the selected code.";
  }
});
window.addEventListener("popstate", restore);
restore();
</script>
</body></html>
```
