See if the object has a contentEditable div

I am trying to check if the content accessible div is focused, but I have problems. Here is my code:

if ($("#journal-content:focus")) { alert("Has Focus"); } else { alert("Doesn't Have Focus"); } 

The problem is that it always returns β€œFocus”, even if it is not. What is the best way to do this?

Update:. The reason for this is to see if the cursor is in the right place before inserting a new element. Otherwise, if the last place the user clicked was in the header, then when I restore the selection with Rangy and replace it with a new element, it gets into the header. I need a way to find out if the contenteditable div is focused / has a cursor in it, so if not, I will just add the element that I insert at the end.

Update 2: Here JSFiddle illustrates my problem: http://jsfiddle.net/2NHrM/

+7
source share
4 answers

Try:

 if ($("#journal-content").is(":focus")) { alert("Has Focus"); } else { alert("Doesn't Have Focus"); } 

Or:

 window.contenteditable_focused = false; $("#journal-content").focus(function() { //alert("Has Focus"); contenteditable_focused = true; }); $("#journal-content").blur(function() { //alert("Doesn't Have Focus"); contenteditable_focused = false; }); 

Check contenteditable_focused before running the script.

Or:

 if ($( document.activeElement ).is("#journal-content")) { alert("Has Focus"); } else { alert("Doesn't Have Focus"); } 
+9
source

For pure JavaScript, when you have multiple content elements:

CSS and markup are for fragment only

Try to run the fragment and clicking on any element.

 function isFocused() { if (document.activeElement.id == "journal-content") { alert("Focused!"); } else { alert("Not focused :("); } } 
 #journal-content { background-color: #eee; } #not-journal-content { background-color: #ccc; } 
 <div id="journal-content" contenteditable="true" onclick="isFocused()">Journal Content</div> <div id="not-journal-content" contenteditable="true" onclick="isFocused()">Not Journal Content</div> 
+3
source

How about this ?:

 if (document.activeElement.isContentEditable) { ... } 

I don’t know how well the browser is supported, but at least Chrome and Firefox support it.

+2
source

You can try this

 if ($("#journal-content").is(":focus")) { ... 

Maybe if you tell us what you are trying to achieve, we will help more. Meanwhile, you can read it here: http://api.jquery.com/focus-selector/ .

0
source

All Articles