Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent contenteditable auto-focus on Enter keypress on Chrome

I have a contenteditable div on which I control the behavior of some keys. In particular, I have this:

$('#my_contenteditable').on('keydown', function(e) {
  // Some code...
  if (e.key == 'Enter') {
    $(this).blur();
    e.preventDefault();
    return;
  }
  // Some more code...
});

But after I blured the element, when I press Enter again, Chrome wants to re-focus it.

JSFiddle demo here

Can I prevent this behavior?

like image 320
Mat Avatar asked Nov 16 '25 01:11

Mat


1 Answers

if (e.keyCode == 13) {
    e.preventDefault()
    e.target.blur()
    window.getSelection().removeAllRanges()
}
like image 136
Kilmyashkin Avatar answered Nov 18 '25 14:11

Kilmyashkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!