1

I have a sample at Finding currently focused span in an editable div.

The editable div i.e. a div having the attribute contenteditable="true", contains 3 different spans with each span wrapped in a div. A user could position the cursor in any one of the three spans. My goal is to find out which span is being edited when user clicks on a span content to start editing or types into it. I would like this to work on desktop or mobile devices.

I tried getting the span using document.activeElement as you can see in my code sample, but it gets the editable div and not the current span. I was looking for a JavaScript solution to this problem.

Question: How would I get the id of span element whose text is being edited using JavaScript?

Html code

<div id="input" contenteditable="true" onfocus="findCurrentSpan(this)">
  <div>
    <span id="first">first span</span>
  </div>
  <div>
    <span id="second">second span</span>
  </div>
  <div>
    <span id="third">third span</span>
  </div>
</div>
<p id="info" style="color:green">

</p>

Javascript code

function findCurrentSpan(editor) {
var element = document.getElementById("input");
var currentSpan = document.activeElement;
document.getElementById("info").innerHTML = "Active element's id is " + currentSpan.id;

}

Sunil
  • 20,653
  • 28
  • 112
  • 197

2 Answers2

0

The Problem is, that you are going to select the active element from the whole Page, that's why it is called document.activElement.

Have a look a this SO Question Get and set cursor position with contenteditable div

grisuu
  • 189
  • 1
  • 9
0

In your example findCurrentSpan(this) this is referring to the function findCurrentSpan() so this.id will have the value input.

 <div id="input" contenteditable="true" onfocus="findCurrentSpan(this)">

To solve your problem, I recommend you bind an onfocus event to all of input's children (explanation on how the onfocus event works in javascript).

This is how you select all the span elements inside input:

var children = document.getElementById("input").querySelectorAll('span');

After selecting the elements you want to bind an event to. Use a loop to bind an event to all the elements. As far as I know span doesn't implement a focus state so we will have to use click.

children.forEach(function(e) {
    document.getElementById(e.id).addEventListener("click", findCurrentSpan)
})

The code will look like this:

function findCurrentSpan() {
    console.log(this.id)
    document.getElementById("info").innerHTML = "Active element's id is " + this.id;
}

var children = document.getElementById("input").querySelectorAll('span');
children.forEach(function(e){
    document.getElementById(e.id).addEventListener("click", findCurrentSpan)
})
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Roe
  • 633
  • 2
  • 14