4

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?

Will Whitney
  • 127
  • 1
  • 8

3 Answers3

4

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('&nbsp;');} 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.

Community
  • 1
  • 1
Joel
  • 2,654
  • 6
  • 31
  • 46
1
event.preventDefault()

is what saved me. In the keyPress function have an event.preventDefault and the onClick should not be called.

0

I had a similar problem with Firefox 31 and 32. Typing space opened the alert-box. Solution: Replace onclick with onmousedown.

gehrd
  • 9
  • 1