Skip to content Skip to sidebar Skip to footer

Chrome Firing Onclick When Space Typed In Contenteditable Button

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 butt

Solution 1:

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:

<buttoncontenteditable="true"onclick="if (!event.x && !event.y && !event.clientX && !event.clientY) {event.preventDefault(); insertHtmlAtCursor('&nbsp;');} else {alert('wtf?');}">Edit me!</button><scripttype="text/javascript">functioninsertHtmlAtCursor(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');
    } elseif (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.

Solution 2:

event.preventDefault()

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

Solution 3:

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

Post a Comment for "Chrome Firing Onclick When Space Typed In Contenteditable Button"