Last active
August 29, 2015 14:10
-
-
Save aleemb/cf3d142e5095b49eb529 to your computer and use it in GitHub Desktop.
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Suggestions</title> | |
<style> | |
#menu { | |
margin: 0; | |
width: 200px; | |
display: none; | |
position: absolute; | |
} | |
#menu ul { | |
margin: 0; | |
padding: 0; | |
list-style: none; | |
} | |
#menu li { | |
padding: 5px; | |
border: 1px gray solid; | |
border-bottom: none; | |
} | |
#menu li:last-child { | |
border-bottom: 1px gray solid; | |
} | |
#editor { | |
margin: 20px auto; | |
width: 680px; | |
max-width: 96%; | |
outline: none; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="editor" contenteditable> | |
<p>Enter text here.</p> | |
</div> | |
<div id="menu"> | |
<ul> | |
<li>#167 Thing</li> | |
<li>#32 That one bug</li> | |
<li>#84 That other bug</li> | |
</ul> | |
</div> | |
<script> | |
var editor = document.querySelector('#editor'), | |
menu = document.querySelector('#menu') | |
function placeMenu () { | |
var sel = window.getSelection(), | |
range, | |
bounds | |
if (!sel.rangeCount) return | |
range = sel.getRangeAt(0) | |
bounds = range.getClientRects()[0] | |
menu.style.top = (bounds.bottom + window.pageYOffset) + 'px' | |
menu.style.left = bounds.left + 'px' | |
menu.style.display = 'block' | |
} | |
// Note: the menu doesn’t get hidden when pressing keys that do not | |
// trigger keypress events, like backspace, arrow keys, etc. | |
// Obviously, this needs much polishing. | |
editor.addEventListener('keypress', function (e) { | |
if (String.fromCharCode(e.which) !== '#') { | |
menu.style.display = 'none' | |
return | |
} | |
/** | |
* We have to wait until the character actually appears, or the menu | |
* will be too much to the left. If you’re really picky about it, | |
* you might want to use something a little faster than setTimeout | |
* in production, like this setImmediate polyfill, | |
* https://github.com/YuzuJS/setImmediate | |
* as setTimeout(fn, 0) can actually introduce a perceptible delay. | |
*/ | |
setTimeout(placeMenu, 0) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment