Skip to content

Instantly share code, notes, and snippets.

@amundo
Created January 18, 2024 18:43
Show Gist options
  • Save amundo/149c63b23e7777b43e04fca62491334a to your computer and use it in GitHub Desktop.
Save amundo/149c63b23e7777b43e04fca62491334a to your computer and use it in GitHub Desktop.
WebCOLD 04
<super-slider unit="em" target=".preview h1">
<label for="title-size">Title font size</label>
<input id="title-size" type="range" min="0.5" max="4" step="0.1" value="2" />
</super-slider>
<super-slider unit="em" target=".preview h2">
<label>Subtitle font size</label>
<input type="range" min="0.5" max="2.5" step="0.1" value="1.5" />
</super-slider>
<div class="preview">
<h1>This is a title</h1>
<h2>This is a subtitle</h2>
</div>
class superSlider extends HTMLElement {
connectedCallback() {
let targetEl = document.querySelector(this.getAttribute("target"));
let unit = this.getAttribute("unit");
let slider = this.querySelector('input[type="range"]');
slider.addEventListener("input", (e) => {
targetEl.style.setProperty("font-size", slider.value + unit);
readout.textContent = slider.value + unit;
});
let reset = slider.getAttribute("value");
let resetter = document.createElement("button");
resetter.textContent = "↺";
resetter.setAttribute("title", reset + unit);
resetter.addEventListener("click", (e) => {
slider.value = reset;
slider.dispatchEvent(
new MouseEvent("input", { view: window, bubbles: false })
);
});
slider.after(resetter);
let label = this.querySelector("label");
let readout = document.createElement("span");
readout.classList.add("readout");
readout.textContent = slider.value + unit;
label.after(readout);
if (!label.getAttribute("for") && slider.getAttribute("id")) {
label.setAttribute("for", slider.getAttribute("id"));
}
if (label.getAttribute("for") && !slider.getAttribute("id")) {
slider.setAttribute("id", label.getAttribute("for"));
}
if (!label.getAttribute("for") && !slider.getAttribute("id")) {
let connector = label.textContent.replace(" ", "_");
label.setAttribute("for", connector);
slider.setAttribute("id", connector);
}
}
}
customElements.define("super-slider", superSlider);
/* decorative styles not directly related to the example follow */
.preview {
border: 1px solid;
padding: 1em;
background: #eee;
}
.preview h1 {
margin: 0;
}
super-slider {
display: flex;
align-items: center;
margin-block: 1em;
}
super-slider input[type="range"] {
margin-inline: 0.25em 1px;
}
super-slider .readout {
width: 3em;
margin-inline: 0.25em;
padding-inline: 0.5em;
border: 1px solid #0003;
background: #EEE;
font: 1em monospace;
text-align: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment