Remove focus from div editable content

If I programmatically remove the focus of the content being edited by the div, it looks like it has no focus, but then if the user types it, it still has focus.

$("#myContentEditable").focus(); $("#myContentEditable").blur(); 

If you start typing, he still has focus.

https://jsfiddle.net/zvn4w61d/

This does not occur when entering text.

Any idea how to remove focus?

I suppose I can give a different focus for text input, but Id should create it on the fly, focus it and destroy it. A little hack, if not ....

+6
source share
3 answers

You can use a selection object representing a range of text selected by the user, or the current caret position along with removeAllRanges, to remove all ranges from the selection:

 window.getSelection().removeAllRanges(); 

Working demo

+7
source

Add this code to your main javascript file and all content components will work fine.

 $(function(){ $(document).on('mousedown', '[contenteditable]', function(e){ $(this).attr('contenteditable', true); $(this).focus(); }); $(document).on('blur', '[contenteditable]', function(e){ $(this).attr('contenteditable', false); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div contenteditable>This is a content editable div that the blur really works</div> 
+2
source

You can do it with CSS

try it

 #myContentEditable:read-write:focus { outline: none; } 

Demo here

0
source

All Articles