I have a button with contenteditable=true
. I can edit the text just fine, but I cannot type spaces in Chrome. When I hit spacebar, Chrome instead fires an onClick event on the button. Safari, however, inserts a space just as you would expect.
With this code, trying to type a space while editing the button triggers the alert in Chrome.
<button
contenteditable="true"
onclick="alert('wtf?');">Edit me!</button>
Fiddle with this code: http://jsfiddle.net/Jrt8w/1/
Why is Chrome pretending that was a click event? And how can I convince it to instead insert a space?
This is a harder problem than appears. There doesn't seem to be any way to turn off the space key "clicking" the button, so this is an attempt at emulation:
<button
contenteditable="true"
onclick="if (!event.x && !event.y && !event.clientX && !event.clientY) {event.preventDefault(); insertHtmlAtCursor(' ');} else {alert('wtf?');}">Edit me!</button>
<script type="text/javascript">
function insertHtmlAtCursor(html) {
var range, node;
if (window.getSelection && window.getSelection().getRangeAt) {
range = window.getSelection().getRangeAt(0);
node = range.createContextualFragment(html);
range.insertNode(node);
window.getSelection().collapseToEnd();
window.getSelection().modify('move', 'forward', 'character');
} else if (document.selection && document.selection.createRange) {
document.selection.createRange().pasteHTML(html);
document.selection.collapseToEnd();
document.selection.modify('move', 'forward', 'character');
}
}
</script>
You can see it working here.
I copied the meat of my code from this answer. Please note that I've only tested in Chrome. Not sure if it will work in IE, and if not, I'd use a library like Rangy, mentioned in the answer I linked above. Either way, this should give you a good starting point.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With