I have a textarea on my page. If user on Windows (not sure about Mac behavior though) will open built-in Emoji menu (Win + .
) in that textarea and click on any emoji, the textInput
event will be fired. I need to, somehow, prevent default behavior for this event, which is inserting an emoji to the input, and resolve emoji insertion on my side. However, event.preventDefault()
doesn't work in this case. Any ideas?
Asked
Active
Viewed 87 times
0
-
1Don't catch the event, instead, detect the emoji in the input, delete it, and replace it with any custom behavior – mousetail Feb 02 '23 at 12:43
-
@mousetail that's interesting approach, will see into that. The one problem I can see so far is how to detect an emoji? – Andrew Feb 02 '23 at 12:44
-
That's a completely different problem that has plenty of answers on this site – mousetail Feb 02 '23 at 12:45
-
2https://stackoverflow.com/questions/18862256/how-to-detect-emoji-using-javascript – mplungjan Feb 02 '23 at 12:45
-
Thank you! Anyway, I am still wondering if there is a way to just prevent inserting emojis. If I want to disable it for some input, I should be able to do that easily, without writing a ton of additional logic with detecting and deleting emojis – Andrew Feb 02 '23 at 12:50
-
Emoji is just a specific case. The question is about preventing `textInput` event from doing its thing – Andrew Feb 02 '23 at 14:47
-
And this is crucial, because in windows we not only have Emojis in that menu, but also GIFs and applying them in inputs causes stupid bugs – Andrew Feb 02 '23 at 14:48
-
Reopened. Please change the text of the question to match your requirements. The one you asked has been handled using a workaround but I will be interested in seeing how you will preventDefault on a process that does not trigger an event you can prevent. – mplungjan Feb 02 '23 at 14:54
-
_"The question is about preventing textInput event from doing its thing"_ - when you say "textInput" event, you mean the actual `input` event? That is not cancelable, so no, you can not prevent the insertion of anything via _that_. – CBroe Feb 02 '23 at 14:58
1 Answers
1
I do not think you can handle the emoji interface using preventDefault.
We cannot detect the combination of event.key==="Meta" and "."
Here is how to handle it after the fact:
const re = /\p{Emoji}|\p{Emoji_Presentation}|\p{Extended_Pictographic}/ug; // can be extended
document.getElementById('myField').addEventListener('input', function(e) {
const val = this.value;
this.value = val.replace(re,"");
})
<textarea id="myField"></textarea>
the script above is from combining the information from the answers below

mplungjan
- 169,008
- 28
- 173
- 236