Skip to content

Instantly share code, notes, and snippets.

@danielgavrilov
Created July 8, 2016 15:47
Show Gist options
  • Save danielgavrilov/a2001b028c655b46b997167320fb44fb to your computer and use it in GitHub Desktop.
Save danielgavrilov/a2001b028c655b46b997167320fb44fb to your computer and use it in GitHub Desktop.
custom caret
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
svg { width:100%; height: 100% }
.output { font-size: 36px; font-weight: bold; }
.caret { background-color: steelblue; width: 3px; height: 10px; position: absolute; }
</style>
</head>
<body>
<script>
var body = d3.select(document.body);
var input = body.append("input")
.attr("type", "text");
var output = body.append("div")
.append("span")
.attr("class", "output");
function updateCaret() {
var { top, right, height } = output.node().getBoundingClientRect();
caret.style("top", top)
.style("left", right)
.style("height", height)
.style("width", (input.node().selectionEnd - input.node().selectionStart) * 20 || 3)
}
var caret = body.append("div")
.attr("class", "caret");
var delayedUpdateCaret = function() { setTimeout(updateCaret, 10) };
input.on("input", function() {
output.text(this.value.replace(" ", "\xa0"));
updateCaret();
});
input.on("focus", function() {
caret.style("display", "block");
});
input.on("blur", function() {
caret.style("display", "none");
});
updateCaret();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment