Created
November 27, 2016 17:02
-
-
Save bitdivine/cb268d5935504ceee6102f4ea7442536 to your computer and use it in GitHub Desktop.
Rich text editor as a form input (WYSIWYG contenteditable)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function(){ | |
| // This is a WYSIWYG editing div that can be used as in input in a form. | |
| // Usage: <div contenteditable is="with-input" name="..."></div> | |
| // This can be used in a form and values will be submitted as with a text input. | |
| // You can also get the input with: | |
| // Array.from(document.querySelectorAll('input')).reduce((d,e) => {d[e.name]=e.value;return d;}, {}); | |
| // The div is a visual component. An invisible input is appended to | |
| // hold the form data. Any changes made to the div will change the | |
| // value of the input element. | |
| const global = window; | |
| var MutationObserver = global.MutationObserver || global.WebKitMutationObserver || global.MozMutationObserver; | |
| try { | |
| var proto = Object.create(HTMLDivElement.prototype); | |
| proto.createdCallback = function() { | |
| var self = this; | |
| // The input element: | |
| var input = this.input = document.createElement('input'); | |
| input.setAttribute('type','text'); | |
| input.setAttribute('name',this.getAttribute('name')); | |
| input.setAttribute('value',this.innerHTML); | |
| input.style.display = 'none'; | |
| this.insertAdjacentElement('afterend', input); | |
| // Update the input element on edit: | |
| var observer = this.observer = new MutationObserver((mutations) => input.value = this.innerHTML); | |
| observer.observe(this, { childList: true, characterData: true, subtree: true }); | |
| // Want changes in the input to be refelected in the div but this part doesn't work yet: | |
| input.addEventListener("change", () => this.innerHTML = input.value); | |
| }; | |
| var nCB = document.registerElement("with-input", { | |
| prototype: proto, | |
| extends: 'div' | |
| }); | |
| } catch(e){console.error(e.message)} | |
| })(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: https://jsfiddle.net/bitdivine/35rz76tb/2/