Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

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.

+ add another resource

Packages

Add Packages

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.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Progressively Enchanced Stepper Web Component</h1>

<div class="two-up">
<form class="form" id="quantity-form" action="#">
  <div class="field">
    <label for="stepper">Quantity 1 (using data-is)</label>
    <input type="number" id="stepper" name="quantity-1" value="0" data-is="my-stepper">
  </div>
  <div class="field">
    <label for="stepper2">Quantity 2 (input as child)</label>
    <my-stepper>
      <input type="number" id="stepper2" name="quantity-2" value="0">
    </my-stepper>
  </div>
  <div class="field">
    <button class="button">Check form data</button>
  </div>
</form>

<div class="result">
  <h2>Form Data</h2>
  <pre id="report"></pre>
</div>
</div>

<p>This is my attempt at upgrading a form element to an enhanced Web Component. The benefit here is if JavaScript doesn't load, the input functions like a plain old number input.</p>
<p>Since the inputs never leave the light DOM, they work seamlessly. IDs work with the labels, the form detects the values, etc.</p>
              
            
!

CSS

              
                html {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  line-height: 1.5;
}

p {
  max-width: 60ch;
}

input[type=number] {
  -moz-appearance: textfield;
  text-align: center;
  border: solid 2px black;
  border-radius: 6px;
  max-width: 75px;
}

my-stepper:defined input[type=number]::-webkit-inner-spin-button, 
my-stepper:defined input[type=number]::-webkit-outer-spin-button { 
  -webkit-appearance: none; 
  margin: 0; 
}

my-stepper::part(wrapper) {
  position: relative;
}

my-stepper::part(control) {
  position: absolute;
  -webkit-appearance: none;
  background: transparent;
  border: none;
  height: 100%;
  top: 1px;
}

my-stepper::part(increment) {
  right: 0;
}

.form {
  background-color: #eee;
  padding: 1.5rem;
}

.form > * + * {
  margin-top: 0.75rem;
}

.field label {
  display: block;
  font-weight: 700;
}

.field > * + * {
  margin-top: 0.25rem;
}

.button {
  -webkit-appearance: none;
  border: none;
  font: inherit;
  font-weight: 700;
  color: white;
  background-color: #333;
  border-radius: 6px;
}

.result {
  padding: 1.5rem;
}

.result > * {
  margin: 0;
}

.result > * + * {
  margin-top: 0.75rem;
}

.two-up {
  display: flex;
  width: min(100%, 80ch);
  flex-wrap: wrap;
}

.two-up > * {
  flex-grow: 1;
}

              
            
!

JS

              
                //const template = document.createElement("template");
// template just for transferring innerHTML is a waste of resources
// the (old) blogs did this only to show what TEMPLATEs are

class MyStepper extends HTMLElement {
  static validateElement(el) {
    if (notNumberInput(el)) throw new Error("Must be an input of type number!");
  }

  constructor() {
    // all can be chained
    super().attachShadow({ mode: "open" }).innerHTML = `
<span part="wrapper">
  <button part="decrement control" tabindex="-1" aria-hidden="true">&minus;</button>
  <slot>REPLACE ME</slot>
  <button part="increment control" tabindex="-1" aria-hidden="true">+</button>
<span>`;
    // shadowRoot exists in Memory so can do all DOM stuff in the constructor
    // blogs that say "do it in connectedCallback" don't understand the constructor+shadowDOM
    // inline listeners are shorter and easier.. there is no risk any other code is going to overwrite them
    this.shadowRoot.querySelector("[part*=decrement]").onclick = (evt) =>
      this.decrement(evt);
    this.shadowRoot.querySelector("[part*=increment]").onclick = (evt) =>
      this.increment(evt);
  }

  connectedCallback() {
    // this.increment = this.increment.bind(this);
    // bind is oldskool, just make sure you CALL the function in the above .onclick handler with an arrow function (sets lexical this scope); not REFERENCE it
  }

  disconnectedCallback() {
    // bla bla.removeEventListener("click", this.decrement);
    // no need, all listeners are INSIDE the Element, so Garbage Collection removes them when the Element is removed
  }

  // Fine if you want to call these methods from the OUTSIDE; although I would suggest "stepUp" instead of "increment" then to match functionality
  // otherwise whack them (as functions) in the constructor-onclicks
  increment(event) {
    if (this.firstElementChild) {
      this.firstElementChild.stepUp();
    }
  }

  decrement(event) {
    if (this.firstElementChild) {
      this.firstElementChild.stepDown();
    }
  }
}

//  end of Danny comments


customElements.define("my-stepper", MyStepper);

function notNumberInput(el) {
  return !(el instanceof HTMLInputElement && el.type === "number");
}

document.querySelectorAll("[data-is]").forEach((el) => {
  console.warn("Something is happening",el)
  const cEl = el.dataset.is; // get string CustomElement name
  delete el.dataset.is;

  if (cEl) {
    const CElement = customElements.get(cEl);
    CElement.validateElement?.(el); // throws Error if not type=number
    const cElInstance = new CElement();// this will trigger the constructor
    
    el.after(cElInstance); // inserts the element in DOM after <input>, triggers connectedCallback
    cElInstance.append(el); // then appends/moves <input> to lightDOM
    // I would move these to a method on the Element; like validateElement is
    // thinking out loud.. maybe pass cEl/el to the constructor: new CElement(el)
    // ?? and then the constructor can validate and append itself .. keep all code in one place
  }
});

// form stuff here
const form = document.getElementById("quantity-form");

form.addEventListener("submit", function (event) {
  event.preventDefault();

  const data = new FormData(form);
  const entryObj = {};
  const reportDiv = document.getElementById("report");

  for (const [key, value] of data.entries()) {
    entryObj[key] = value;
  }

  reportDiv.textContent = JSON.stringify(entryObj, null, 2);
});

              
            
!
999px

Console