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 is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <div class="container">
		<div id="editor" contenteditable="true">
</div>
              
            
!

CSS

              
                body {
	background-color: #131313;
}

#editor {
	width: 600px!important;
	height: 200px!important;
		color: #333;
	background-color: #fff;
  position: relative;
	padding: 10px 0 0 10px;
	font-family: Arial;
  font-size: 20px;
  outline: none;
  transition: all 0.4s ease;
  -webkit-transition: all -webkit-transform 0.4s ease;
  text-overflow: ellipsis;
}

@-moz-document url-prefix() {
  #autoComplete {
    border-width: 1px;
    background-size: 1.2rem;
    background-origin: border-box;
    background-position: center;
  }
}
              
            
!

JS

              
                // autoComplete.js: [MODIFIED]
(function(global, factory) {

	typeof exports === 'object' 
	&&
		typeof module !== 'undefined' ? 
		module.exports = factory() 
	:
	typeof define === 'function'
	&&
		define.amd ?
		define(factory)
	:
	( global.autoComplete = factory() );

}(this, (function() {

	'use strict';

	function _classCallCheck(instance, Constructor) {
		if (!(instance instanceof Constructor)) {
			throw new TypeError("Cannot call a class as a function");
		}
	}

	function _defineProperties(target, props) {
		for (var i = 0; i < props.length; i++) {
			var descriptor = props[i];
			descriptor.enumerable = descriptor.enumerable || false;
			descriptor.configurable = true;
			if ("value" in descriptor) descriptor.writable = true;
			Object.defineProperty(target, descriptor.key, descriptor);
		}
	}

	function _createClass(Constructor, protoProps, staticProps) {
		if (protoProps) _defineProperties(Constructor.prototype, protoProps);
		if (staticProps) _defineProperties(Constructor, staticProps);
		return Constructor;
	}

	var dataAttribute = "data-result";
	var select = {
		resultsList: "autoComplete_results_list",
		result: "autoComplete_result",
		highlight: "autoComplete_highlighted"
	};

	function getInput(selector) {
		return typeof selector === "string" ? document.querySelector(selector) : selector();
	};

	// Runs just once, on initial startup
	function createResultsList(renderResults) {

		var resultsList = document.createElement(renderResults.element);
		resultsList.setAttribute("id", select.resultsList);

		if (renderResults.container) {
			renderResults.container(resultsList);
		}

		renderResults.destination.insertAdjacentElement(renderResults.position, resultsList);

		return resultsList;
	};

	function highlight(value) {

		console.log(" [>>] highlight()::value: ", value );
		return "<span class=".concat(select.highlight, ">").concat(value, "</span>");

	};

	function addResultsToList(resultsList, dataSrc, resultItem) {

		// #suggestion__container === resultsList
		// dataSrc === Array of Matches
		// resultItem === { content: "", element: "" }

		dataSrc.forEach(function(event, record) {

			var result = document.createElement(resultItem.element);
			var resultValue = dataSrc[record].value[event.key] || dataSrc[record].value;
			result.setAttribute(dataAttribute, resultValue);
			result.setAttribute("class", select.result);
			result.setAttribute("tabindex", "1");
			if ( resultItem.content ){

				resultItem.content(event, result);

			} else {

				result.innerHTML = event.match || event;

			}

			resultsList.appendChild(result);

		});

	};

	function navigation(selector, resultsList) {
		var input = getInput(selector);
		var first = resultsList.firstChild;
		document.onkeydown = function(event) {
			var active = document.activeElement;
			switch (event.keyCode) {
				case 38:
					if (active !== first && active !== input) {
						active.previousSibling.focus();
					} else if (active === first) {
						input.focus();
					}
					break;
				case 40:
					if (active === input && resultsList.childNodes.length > 0) {
						first.focus();
					} else if (active !== resultsList.lastChild) {
						active.nextSibling.focus();
					}
					break;
			}
		};
	};

	function clearResults(resultsList) {
		return resultsList.innerHTML = "";
	};

	function getSelection(field, resultsList, callback, resultsValues) {
		var results = resultsList.querySelectorAll(".".concat(select.result));
		Object.keys(results).forEach(function(selection) {
			["mousedown", "keydown"].forEach(function(eventType) {
				results[selection].addEventListener(eventType, function(event) {
					if (eventType === "mousedown" || event.keyCode === 13 || event.keyCode === 39) {
						callback({
							event: event,
							query: getInput(field) instanceof HTMLInputElement ? getInput(field).value : getInput(field).innerHTML,
							matches: resultsValues.matches,
							results: resultsValues.list.map(function(record) {
								return record.value;
							}),
							selection: resultsValues.list.find(function(value) {
								var resValue = value.value[value.key] || value.value;
								return resValue === event.target.closest(".".concat(select.result)).getAttribute(dataAttribute);
							})
						});
						clearResults(resultsList);
					}
				});
			});
		});
	};

	var autoCompleteView = {
		getInput: getInput,
		createResultsList: createResultsList,
		highlight: highlight,
		addResultsToList: addResultsToList,
		navigation: navigation,
		clearResults: clearResults,
		getSelection: getSelection
	};

	// Custom Event Polyfill SECTION
	function CustomEventPolyfill(event, params) {
		params = params || {
			bubbles: false,
			cancelable: false,
			detail: undefined
		};
		var evt = document.createEvent("CustomEvent");
		evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
		return evt;
	};

	CustomEventPolyfill.prototype = window.Event.prototype;

	var CustomEventWrapper = typeof window.CustomEvent === "function" && window.CustomEvent || CustomEventPolyfill;

	function initElementClosestPolyfill() {
		if (!Element.prototype.matches) {
			Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;
		}
		if (!Element.prototype.closest) {
			Element.prototype.closest = function(s) {
				var el = this;
				do {
					if (el.matches(s)) {
						return el;
					}
					el = el.parentElement || el.parentNode;
				} while (el !== null && el.nodeType === 1);
				return null;
			};
		}
	};

	var Polyfill = {
		CustomEventWrapper: CustomEventWrapper,
		initElementClosestPolyfill: initElementClosestPolyfill
	};
	// Custom Event Polyfill SECTION

	var autoComplete =
			function() {
				function autoComplete(config) {
					_classCallCheck(this, autoComplete);
					this.selector = config.selector || "#autoComplete";
					this.data = {
						src: function src() {
							return typeof config.data.src === "function" ? config.data.src() : config.data.src;
							console.log( "src()::config.data.src:", config.data.src );

						},
						key: config.data.key,
						cache: typeof config.data.cache === "undefined" ? true : config.data.cache
					};
					this.query = config.query;
					this.searchEngine = config.searchEngine === "loose" ? "loose" : "strict";
					this.customEngine = config.customEngine ? config.customEngine : false;
					this.threshold = config.threshold || 0;
					this.debounce = config.debounce || 0;
					this.resultsList = {
						render: config.resultsList && config.resultsList.render ? config.resultsList.render : false,
						view: config.resultsList && config.resultsList.render ? autoCompleteView.createResultsList({
							container: config.resultsList && config.resultsList.container ?
							config.resultsList.container : false,
							destination: config.resultsList && config.resultsList.destination ?
							config.resultsList.destination : autoCompleteView.getInput(this.selector),
							position: config.resultsList && config.resultsList.position ?
							config.resultsList.position : "afterend",
							element: config.resultsList && config.resultsList.element ? config.resultsList.element : "ul"
						}) : null
					};
					this.sort = config.sort || false;
					this.placeHolder = config.placeHolder;
					this.maxResults = config.maxResults || 5;
					this.resultItem = {
						content: config.resultItem && config.resultItem.content ? config.resultItem.content : false,
						element: config.resultItem && config.resultItem.element ? config.resultItem.element : "li"
					};
					this.noResults = config.noResults;
					this.highlight = config.highlight || false;
					this.onSelection = config.onSelection;
					this.dataSrc;
					this.init();
				}

				_createClass(autoComplete, [{

					key: "search",

					value: function search(query, record) {
						var recordLowerCase = record.toLowerCase();
						if (this.searchEngine === "loose") {
							query = query.replace(/ /g, "");
							var match = [];
							var searchPosition = 0;
							for (var number = 0; number < recordLowerCase.length; number++) {
								var recordChar = record[number];
								if (searchPosition < query.length && recordLowerCase[number] === query[searchPosition]) {
									recordChar = this.highlight ? autoCompleteView.highlight(recordChar) : recordChar;
									searchPosition++;
								}
								match.push(recordChar);
							}
							if (searchPosition !== query.length) {
								return false;
							}
							return match.join("");
						} else {
							if (recordLowerCase.includes(query)) {
								var pattern = new RegExp("".concat(query), "i");
								query = pattern.exec(record);
								return this.highlight ? record.replace(query, autoCompleteView.highlight(query)) : record;
							}
						}
					}

				}, {

					key: "listMatchedResults",

					value: function listMatchedResults(data) {

						var _this = this;

						return new Promise(function(resolve) {
							var resList = [];
							data.filter(function(record, index) {
								var search = function search(key) {
									var match = _this.customEngine ? _this.customEngine(_this.queryValue, record[key] || record) : _this.search(_this.queryValue, record[key] || record);
									if (match && key) {

										resList.push({
											key: key,
											index: index,
											match: match,
											value: record
										});
									} else if (match && !key) {

										resList.push({
											index: index,
											match: match,
											value: record
										});
									}
								};
								if (_this.data.key) {
									var _iteratorNormalCompletion = true;
									var _didIteratorError = false;
									var _iteratorError = undefined;
									try {
										for (var _iterator = _this.data.key[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
											var key = _step.value;
											search(key);
										}
									} catch (err) {
										_didIteratorError = true;
										_iteratorError = err;
									} finally {
										try {
											if (!_iteratorNormalCompletion && _iterator["return"] != null) {
												_iterator["return"]();
											}
										} finally {
											if (_didIteratorError) {
												throw _iteratorError;
											}
										}
									}
								} else {
									search();
								}
							});
							var list = _this.sort ? resList.sort(_this.sort).slice(0, _this.maxResults) : resList.slice(0, _this.maxResults);
							if (_this.resultsList.render) {
								autoCompleteView.addResultsToList(_this.resultsList.view, list, _this.resultItem);
								autoCompleteView.navigation(_this.selector, _this.resultsList.view);
							}
							return resolve({
								matches: resList.length,
								list: list
							});
						});
					}

				}, {

					key: "ignite",
					value: function ignite() {

						let _this2 = this;
						let input = autoCompleteView.getInput(this.selector);

						if (this.placeHolder) {
							input.setAttribute("placeholder", this.placeHolder);
						}

						// Debounce Helper Function:
						function debounce(func, delay) {
							var inDebounce;
							return function() {
								var context = this;
								var args = arguments;
								clearTimeout(inDebounce);
								inDebounce = setTimeout(function() {
									return func.apply(context, args);
								}, delay);
							};
						};
						// Debounce Helper Function:

						function exec(event) {

							// Check if element is input element:
							var inputValue = input instanceof HTMLInputElement ? input.value.toLowerCase() : input.innerHTML.toLowerCase();

							var queryValue = 
									_this2.queryValue = _this2.query && _this2.query.manipulate ?   
									_this2.query.manipulate(inputValue) 
							:
							inputValue;

							// Get word from selection instead of input element:
							let currentSelection = document.getSelection().anchorNode;
							if ( currentSelection.data ){

								let match = currentSelection.data.match(/(\w+?)$/);

								if ( match ){
									queryValue = match[1].toLowerCase();
									console.log( ">> MATCH: <<", queryValue );
									_this2.queryValue = queryValue;
								}

							}

							var renderResultsList = _this2.resultsList.render;

							// threshold: 3 -> triggerCondition
							// Min. Chars length to start Engine:
							var triggerCondition = queryValue.length > _this2.threshold && queryValue.replace(/ /g, "").length;

							// Polyfill EventEmitter:
							function eventEmitter(event, results) {

								input.dispatchEvent(new Polyfill.CustomEventWrapper(
									"autoComplete", {
										bubbles: true,
										detail: {
											event: event,
											input: inputValue,
											query: queryValue,
											matches: results ? results.matches : null,
											results: results ? results.list : null
										},
										cancelable: true
									}
								));

							};
							// Polyfill EventEmitter:

							if ( renderResultsList ) {

								var onSelection = _this2.onSelection;
								var resultsList = _this2.resultsList.view;
								var clearResults = autoCompleteView.clearResults(resultsList);
								if ( triggerCondition ) {

									_this2.listMatchedResults(_this2.dataSrc).then(function(list) {

										eventEmitter(event, list);

										if (list.list.length === 0 && _this2.noResults && _this2.resultsList.render) {

											_this2.noResults();

										} else {

											if (onSelection) {

												autoCompleteView.getSelection(
													_this2.selector, resultsList,
													onSelection,
													list );

											}

										}

									});
								} else {

									eventEmitter(event);

								}

							} else if (!renderResultsList && triggerCondition) {

								_this2.listMatchedResults(_this2.dataSrc).then(function(list) {
									eventEmitter(event, list);
								});

							} else {

								eventEmitter(event);
							}
						};

						input.addEventListener(

							"keyup",

							debounce(function(event) {

								console.log("[>>] keyUp ");

								if (!_this2.data.cache) {
									var data = _this2.data.src();
									if (data instanceof Promise) {
										data.then(function(response) {
											_this2.dataSrc = response;
											exec(event);
										});
									} else {
										_this2.dataSrc = data;
										exec(event);
									}
								} else {
									exec(event);
								}

							}, this.debounce )

						);
					}
				}, {
					key: "init",
					value: function init() {

						let _this3 = this;
						let dataSrc = this.data.src();

						if (dataSrc instanceof Promise) {
							dataSrc.then(function(response) {
								_this3.dataSrc = response;
								_this3.ignite();
							});

						} else {

							this.dataSrc = dataSrc;
							this.ignite();

						}
						Polyfill.initElementClosestPolyfill();
					}
				}]);
				return autoComplete;
			}();

	return autoComplete;

})));

// THIS IS A WIP/PoC.

// Instructions: just start typing one of the `randomWords` and after the threshold of 2 characters (e.g after you type
// the `r` in `agreement`), the autocomplete placeholder will appear. Then just click the placeholder to complete the
// text (this behaviour will be controlled by Tab/Enter in future, but can't be implemented right now as it involves
// modifying the autoComplete.js library.)

// The placeholder doesn't work when formatting is active (e.g press ctrl+b and then try predictive text - it won't
// work).  If you can solve this, fork the pen and contact me for a bounty 😊

const randomWords = [ 'elephant', 'rhinoceros', 'australia', 'reform', 'treaty', 'agreement', 'european union','europe', 'brussels', ' recast', 'domicile', 'america', 'compensation', 'liability','constitution', 'parliament' ];

// Thanks to https://tarekraafat.github.io/autoComplete.js/#/ for providing the core autocomplete engine, which has
// been modified to suit the needs of a rich text editor.
const autoCompletejs = new autoComplete({
	data: {
		src: randomWords,
		cache: false
	},
	// placeHolder: "Food & Drinks...",
	selector: '#editor',
	threshold: 2,
	maxResults: 5,
	resultsList: {
		render: true,
		container: source => {
			source.setAttribute('id', 'suggestion__container');
			source.style.cssText = `display: inline-flex; font-family: Arial; font-size: 20px;
position: absolute;overflow: hidden;opacity: 0.5;z-index: 99999; color: grey;
overflow: hidden;transition: all 0.1s ease-in-out;
-webkit-transition: all -webkit-transform 0.1s ease;`;
		},
		destination: document.querySelector('#editor'),
		element: 'div'
	},
	// XX: resultItem -> Set the source (HTML) of the <span> suggestion element with the matched data
	resultItem: {
		content: (data, source) => {

			// source === #suggestion__container > span

			// [ kostasx ] MODIFIED:
			// source.innerHTML = data.match;
			let lastLength = document.getSelection().anchorNode.data.split(" ").slice(-1)[0].length;
			source.innerHTML = data.match.slice( lastLength-1 );

		},
		element: 'span'
	},
	onSelection: feedback => {

		const editor = document.querySelector('#editor');
		const incompleteText = document.getSelection().anchorNode;
		const range = document.createRange();
		range.selectNodeContents(incompleteText);

		const _incompleteText = incompleteText.textContent;
		let autocompleteText = feedback.results[0];

		autocompleteText = autocompleteText.replace(_incompleteText, '');

		// ??
		let currentSelection = document.getSelection().anchorNode.data;
		let split = currentSelection.split(" ");
		if ( split.length > 1 ){
			let lastLength = split.slice(-1)[0].length;
			autocompleteText = autocompleteText.slice( lastLength );
		}

		insertTextAtCursor( autocompleteText );
		// Call `normalize` on the parent node after inserting the autocomplete text, otherwise 2 separate
		// text nodes will be rendered as the child nodes. These separate nodes may appear visually to be
		// a single word, but if they are not merged it can produce major formatting issues in future.
		editor.normalize();
	}
});

// Hide Results list when not used
document.addEventListener('keydown', e => {
	const resultsList = document.querySelector('#suggestion__container');

	if (e.key && e.key !== 'Backspace') {
		const editor = document.querySelector('#editor');

		// Don't activate predictive text if the caret if the caret has text ahead of it. Things will just get messy.
		if (isCaretAtEnd(editor)) {

			resultsList.style.display = 'inline';
			const incompleteText = window.getSelection().anchorNode;
			// incompleteText === <div id="editor">abc</div>

			if ( incompleteText ) {

				const range = document.createRange();
				range.selectNodeContents( incompleteText );
				range.collapse( false );
				let coordinates = range.getClientRects();
				if ( coordinates.length > 0 ) {
					coordinates = coordinates[0];
					let { top, left } = coordinates;
					// We create the visual effect of a placeholder element by overlaying the suggestion container
					// at the exact position of the incomplete text. Can be a bit buggy but will be improved.

					resultsList.style.top = `${ top }px`;
					resultsList.style.left = `${ left }px`;
				}
			}
		}
	} else {
		resultsList.style.display = 'none';
	}
});

function isCaretAtEnd(element) {
	let atEnd = false,
			selRange,
			testRange;

	if (window.getSelection) {
		const sel = window.getSelection();
		if (sel.rangeCount) {
			selRange = sel.getRangeAt(0);
			testRange = selRange.cloneRange();

			testRange.selectNodeContents(element);
			testRange.setEnd(selRange.startContainer, selRange.startOffset);

			testRange.selectNodeContents(element);
			testRange.setStart(selRange.endContainer, selRange.endOffset);
			atEnd = (testRange.toString() === "");
		}
	}

	return atEnd;
}

function insertTextAtCursor( text ) {

	if ( window.getSelection ) {

		let selection = window.getSelection();
		if ( selection.getRangeAt && selection.rangeCount ) {

			let range = selection.getRangeAt(0);
			window.poop = range;
			range.insertNode( document.createTextNode(text) );
		}
	}

	placeCaretAtEnd(document.querySelector('#editor'));
}

function placeCaretAtEnd(editor) {
	if (typeof window.getSelection !== 'undefined' && typeof document.createRange !== 'undefined') {
		const range = document.createRange();
		range.selectNodeContents(editor);
		range.collapse(false);
		const sel = window.getSelection();
		sel.removeAllRanges();
		sel.addRange(range);
	}
}
              
            
!
999px

Console