Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove focus from a content editable div

If I programatically remove the focus of a content editable div, it looks like it has no focus, but then if the user types it still has focus.

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

If you then start typing, it still has focus.

https://jsfiddle.net/zvn4w61d/

This doesn't happen on text inputs.

Any idea how to actually remove focus?

I suppose I could give another text input focus, but Id have to create it on the fly, focus it, and destroy it. A bit hacky to say the least....

like image 209
Matt Bryson Avatar asked Sep 11 '15 11:09

Matt Bryson


2 Answers

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

window.getSelection().removeAllRanges();

Working Demo

like image 75
Milind Anantwar Avatar answered Oct 02 '22 10:10

Milind Anantwar


Add this code to your main javascript file and all contenteditable 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>
like image 24
Ricardo Azzi Silva Avatar answered Oct 02 '22 10:10

Ricardo Azzi Silva