Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replicate click inside contenteditable <div> with spellcheck

Chrome's native spell check won't work on a contenteditable <div> unless the user clicks into the <div>, which makes sense. But if I'm adding a contenteditable <div> dynamically, is there a way to replicate a user clicking into the <div>> so that the spell check will work? I tried using jQuery:

 $('#div-id').click();

and

 $('#div-id').trigger('click');

but these didn't work. Any help? jQuery or JavaScript works for me.

like image 218
Jack Vawdrey Avatar asked Nov 11 '16 02:11

Jack Vawdrey


1 Answers

As a comment mentioned, bringing focus to the element programmatically will work to enable spellcheck. But this might be undesirable due to the focus now being changed to another element. So here is a complete solution (not using jQuery but will still work with it):

var oldFocus = document.activeElement;

div.focus();

if (oldFocus) {
    oldFocus.focus();
} else {
    div.blur();
}

This saves the previously focused element before focusing the div in order to enable spellcheck. Then, the focus is returned to the old element (if there was one that already had focus), otherwise it makes nothing focused.

like image 174
rvighne Avatar answered Nov 01 '22 06:11

rvighne