Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I blur a div where contentEditable=true?

How can I blur/focusout a div where contentEditable=true? I have attempted $(elm).blur() and $(elm).attr('contentEditable', false);

like image 269
Babiker Avatar asked Feb 02 '11 19:02

Babiker


People also ask

How do you make a div Contenteditable?

Answer: Use the HTML5 contenteditable Attribute You can set the HTML5 contenteditable attribute with the value true (i.e. contentEditable="true" ) to make an element editable in HTML, such as <div> or <p> element.

What is Contenteditable true?

The contenteditable global attribute is an enumerated attribute indicating if the element should be editable by the user. If so, the browser modifies its widget to allow editing.

How do I turn off Contenteditable in HTML?

Just set contentEditable="false" . See this answer.

What is Contenteditable div?

contenteditable is an HTML attribute that you can add to any HTML element. If its value is true or an empty string, that means that the user can edit it by clicking the element. For example: <div contenteditable="true"> Change me! </ div>


3 Answers

I would add another solution that is based on Omnicon's answer which is correct BTW. I have forked his fiddle and updated it.

The trick is to remove all ranges after calling blur:

$(".editable").blur();
window.getSelection().removeAllRanges();
like image 120
Marek Suscak Avatar answered Nov 05 '22 03:11

Marek Suscak


$("div[contentEditable]").blur() to blur all contentEditable elements.

$("#elementId").blur() to blur an element by its id.

like image 26
Roman Resh Avatar answered Nov 05 '22 03:11

Roman Resh


The suggested solution by Roman Resh doesn't work when you click into the element and hit enter immediately after. It won't blur but create line-breaks/divs.

It is possible to prevent this behaviour entirely.

See this fiddle

$('<div class="temp-contenteditable-el" contenteditable="true"></div>') .appendTo('body').focus().remove();

like image 3
Omnicon Avatar answered Nov 05 '22 03:11

Omnicon