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 reactive>REACTIVE!! The time is ${time}</h1>
<h2 reactive>You typed: "${text}"</h2>
<textarea type="text" ref="text" ref-default="() => 'Nothing'"></textarea>
<textarea type="text" ref="text" ref-default="() => 'Nothing'"></textarea>
<p reactive>Randomly generated string : ${random}</p>
              
            
!

CSS

              
                
              
            
!

JS

              
                let __refs__ = {};
let __reactives__ = [];
const reactive = (obj) => {
  //Loop through the string
  Object.keys(obj).forEach((key) => {
    // defineProperty, anyone??
    // We want to maintain reactivity, so we are using custom
    // getters and setters
    Object.defineProperty(__refs__, key, {
      get() {
        return obj[key];
      },
      // This shows an interesting aspect of the logic.
      // This will update the target element everytime
      // something changes.
      set(val) {
        obj[key] = val;
        __updateDOM__(key);
      }
    });
    // Think of this as an initial render
    __updateDOM__(key);
  });
  // This is an important step otherwise
  // everything is useless
  return __refs__;
};
const __updateDOM__ = (ref) => {
  // This is to check whether we want to update a specific ref value
  if (ref) {
    __reactives__
      // filter out the elements we need
      .filter((reactive) => reactive.dataset.ref === ref)
      .forEach((reactive) => {
        let ref = reactive.dataset.ref;
        // Interacting with the DOM
        // Nullish coalescing, anybody?
        reactive.textContent = __refs__[ref] ?? "";
      });
  }
  // UPDATE ALL!!
  else
    __reactives__.forEach((reactive) => {
      let ref = reactive.dataset.ref;
      // Interacting with the DOM
      // Nullish coalescing, anybody?
      reactive.textContent = __refs__[ref] ?? "";
    });
};
(() => {
  // Get live elements
  const __reactiveEl__ = document.querySelectorAll("[reactive]");
  __reactiveEl__.forEach((el) => {
    // Match the `count` between <h1 reactive>${count}</h1>
    const refs = el.innerHTML.match(/\${([^}]+)}/g);
    // If the refs exist
    if (refs) {
      refs.forEach((ref) => {
        // extract it
        const dataRef = ref.split("{")[1].split("}")[0].trim();
        // insert a special span element with the element
        // and store the key name in the `data-ref` attribute
        el.innerHTML = el.innerHTML.replace(
          ref,
          `<span class="reactivity-anywhere" data-ref="${dataRef}"></span>`
        );
      });
      // Push the span element in __reactives__
      __reactives__.push(...el.querySelectorAll("span.reactivity-anywhere"));
    }
  });
  // Initialize all the magic!!
  __updateDOM__();
  const parseDefaultRefValue = (el) => {
    let parsed = null;
    try {
      // If the passed key is a function, run it
      // and store the value
      // I'm sorry, but we need to use eval here
      parsed = eval(`(${el.getAttribute("ref-default")})()`);
    } catch (e) {
      parsed = el.getAttribute("ref-default");
    }
    return parsed;
  };
  const assignDefaultRefsToInputs = (el, ref) => {
    __refs__[ref] = parseDefaultRefValue(el);
  };
  // Select input and textarea elements containing the
  // 'ref' attribute, where the attr. value refers to any
  // key in the __refs__ store, eg.
  // <textarea ref="name"></textarea>
  document.querySelectorAll("input[ref], textarea[ref]").forEach((el) => {
    // Keep a ref to the ref!! Because we don't want to
    // lose it in event listeners
    const ref = el.getAttribute("ref");
    if (ref) {
      // lazily update default values
      window.addEventListener("load", () => assignDefaultRefsToInputs(el, ref));
      el.addEventListener("input", () => {
        // again, a dumb reference to the ref
        const elRef = ref;
        // preserve default value
        const defaultVal = parseDefaultRefValue(el);
        // Set whatever value is typed as the ref value
        // else, the default value
        __refs__[elRef] = el.value !== "" ? el.value : defaultVal;
        if (__refs__[elRef] !== defaultVal) {
          // Keep rest of the input/textarea elements in sync
          Array.from(document.querySelectorAll("input[ref], textarea[ref]"))
            // Find input/textareas with same refs
            .filter((el) => el.getAttribute("ref") === elRef)
            // Keep their value in sync
            .forEach((el) => (el.value = __refs__[elRef]));
        }
      });
    }
  });
})();

// ----------------------------------
// HTML Driver Code
// ----------------------------------
const randomString = (num) => {
  const mappings = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"];
  return num
    .toString()
    .split("")
    .map((el) => mappings[el])
    .join("");
};
const store = reactive({
  time: new Date().toTimeString(),
  text: ""
});
const store2 = reactive({
  random: randomString(Math.random() * 10e10)
});
setInterval(() => {
  store.time = new Date().toTimeString();
  store2.random = randomString(Math.random() * 10e15);
}, 500);

              
            
!
999px

Console