Check to see if the ContentEditable div is currently focused

I'm struggling to determine if a contenteditable div has focus with my current code. Here is what I have so far:

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

The issue I'm encountering is that it always displays "Has focus" even when it shouldn't. What is the most effective approach to resolve this?

Update: I am trying to identify the cursor location in the contenteditable div prior to inserting a new element. If the user last clicked in the header, when I replace the selection and add a new element using Rangy, it remains in the header. Therefore, I need a method to determine if the contenteditable div has focus/the cursor to ensure I insert the element at the end if it doesn't.

Update 2: Check out this JSFiddle to see the problem illustrated: http://jsfiddle.net/2NHrM/

Answer â„–1

Give this a shot:

if ($("#journal-content").is(":focus")) {
    alert("The element has focus");
} else {
    alert("The element does not have focus");
}

Alternatively:

window.contenteditable_focused = false;

$("#journal-content").focus(function() {
    //alert("The element has focus");
    contenteditable_focused = true;
});
$("#journal-content").blur(function() {
    //alert("The element does not have focus");        
    contenteditable_focused = false;
});

Be sure to check contenteditable_focused before running your script.

Or try this:

if ($( document.activeElement ).is("#journal-content")) {
    alert("The element has focus");
} else {
    alert("The element does not have focus");
}

Answer â„–2

How do you feel about this concept?:

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

The level of browser support for this feature is uncertain, but it seems to work well on Chrome and Firefox.

Answer â„–3

When dealing with multiple contenteditable fields in pure JavaScript:

Verify if the current active element is a contenteditable element using document.activeElement.id or

document.activeElement.isContentEditable
.

Here is an example to demonstrate:

function checkFocus() {
  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="checkFocus()">Journal Content</div>
<div id="not-journal-content" contenteditable="true" onclick="checkFocus()">Not Journal Content</div>

Answer â„–4

Give this a shot

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

Perhaps sharing your goal with us will enable us to provide more helpful assistance. In the meantime, you may find this link useful: http://api.jquery.com/focus-selector/.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Using AJAX in PHP will not generate any output when returning JSON

Hey everyone, I'm having trouble with my simple PHP test code. I can't seem to get the err value that I want. 2.php $error = "abc"; $er = json_encode($error); return $er; Here's my HTML: <html> <head> <script src="https:// ...

Extension for Chrome browser

I am new to creating Chrome extensions and I am attempting to build one that will display the IDs of all elements with a specific class name on a website in the popup window. I would like to know if there is a better way to tackle this issue. Thank you for ...

Transforming global CSS into CSS modules: A step-by-step guide

In my nextjs project, I am utilizing react-bootstrap and bootstrap which requires me to include the global css: // _app.js import 'bootstrap/dist/css/bootstrap.min.css'; The issue arises when loading a significant amount of unused css on every p ...

Organizing JSON keys based on their values using Typescript

In the context of a main JSON structure represented below, I am interested in creating two separate JSONs based on the ID and Hobby values. x = [ {id: "1", hobby: "videogames"}, {id: "1", hobby: "chess"}, {id: "2", hobby: "chess ...

Integrating threejs dynamically into a Create React App environment

When I am dynamically loading Three.js, the variable THREE is not found. I have created a React project using create-react-app and copied the three js file into the public folder. Here's the directory structure: src public ├── js │ └─┠...

Ways to showcase a div exclusively on UC mini browser

I'm looking for help to create a script that will only display a div with the class "info-box" in UC Mini browser. This div should be hidden in all other browsers. Can someone assist me with this? <!doctype html> <html> <head> <m ...

Encountering a popup_closed_by_user error while attempting to test Google OAuth within my web application

Currently, I am working on integrating Google login into my web application using AngularJS. Whenever the popup opens up for logging into my Google account or selecting an existing account, I encounter an issue where the popup closes with an error message ...

IE Form SubmissionThe process of submitting a form in

My attempt to prevent form submission in IE 8 using jQuery 1.8.2 by using e.preventDefault(); is not working as expected. $(document).ready(function () { $("form").submit(function (e) { e.preventDefault(); $.ajax({ .... ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

How can I take photos in bulk when I open the camera on Ionic 3?

Is there a way to capture multiple images at once using the camera? Currently, I am only able to capture one image when the user clicks. However, I would like to capture four images when the user clicks the success button. let options: CaptureImageOption ...

What is the best way to delete an added element once a DIV has been toggled with JQuery?

I'm facing an issue where I need to add an element to a DIV that has a toggle function. However, every time I click the toggle again after adding the element, the same element is appended once more, resulting in duplicate elements. Upon observation, ...

Exploring the use of the Next.js page router for implementing internationalization (i18

I need assistance implementing Dutch and English language translations for my entire website. Can anyone provide guidance? I have tried using i18n localizely, but it only works for individual pages. I am looking to implement translations on a larger scale ...

executing minimal tasks when including a new particular category

When my page is loading, the "changed_value" class is not present on the page. I am adding the "changed_value" class in multiple places within the code. Upon adding this class, I want to execute several actions. The issue is that I don't want to man ...

Clicking on components that are stacked on top of each

I am facing an issue with two React arrow function components stacked on top of each other using absolute positioning. Both components have onClick attributes, but I want only the one on top to be clickable. Is there a workaround for this? Here is a simpl ...

Display nested array objects of varying levels within VUE

How do I display nested elements on the UI when dynamically generated based on a parent element's selected option (e.g. List)? For example, in the code below, when creating a field and selecting the List option, another nested should appear, and so o ...

Arrange elements within a division when the division splits into two rows

Currently in my setup: I have a navigation bar with a group of buttons located on the right-hand side. When the navbar is reduced to a smaller size, like on a smartphone, the two buttons get split across 2 rows within the div. In this state, I'm ai ...

What could be causing the block to fail in the event of an AJAX request?

I have encountered an issue with my PHP file and AJAX setup. The if block in my code is working properly, but the else block seems to be not functioning as expected. Even after changing the condition from data!= null to data== null, the problem persists wh ...

Testing the throwing of errors when running Karma by utilizing sinon.spy on global functions like parseInt

I'm currently facing an issue with monitoring the usage of parseInt within my function. This is a Proof of Concept for integrating TypeScript into our company's workflow. I've tried following two different tutorials on testing Sinon, but no ...

Align the camera to be perpendicular with the ground

Ensuring that my fly camera always remains parallel to the ground is crucial to me. Specifically, I need my camera's right vector to always be (1,0,0). To achieve this, I have developed a customized Camera Controller in three.js that simulates unique ...

Continuously improving the form as they evolve

I am interested in creating a form that automatically sends data when users make changes to it. For instance: Imagine a scenario where a moderator is editing an article and changes values in a select field. As soon as the change is made, an ajax request ...