Frage

I have three contenteditabledivs and I want to know ,in which div the user has placed the cursor or caret through tab key or mouse click,

    <div contenteditable="true"></div>
    <div contenteditable="true"></div>
    <div contenteditable="true"></div>

Can somebody help me out?

War es hilfreich?

Lösung

I worked out a better solution ,this will need enclosing all the div tags that you want to check for the cursor into a parent div tag and using the document.getSelection() object we can get the id of the div in which the cursor or caret is placed

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    </head>
    <body>
      <div  id=parent>
            <div contenteditable="true" id=1>dddd
            </div>
            <div contenteditable="true" id=2>dddd
            </div>
            <div contenteditable="true" id=3>dddd
            </div>
      </div>
      <input type="label" id="showRes"></input>
    </body>
    <script type="text/javascript">
var div = document.getElementsByTagName('div');

var out=document.getElementById('parent');

function findCursor(){

var x=document.getSelection();
var r=x.getRangeAt(0);
var tempnode=document.createElement("div");
tempnode.setAttribute("id","cursorhook");
r.surroundContents(tempnode);
document.getElementById('showRes').value=tempnode.parentNode.id;
document.getElementById(tempnode.parentNode.id).removeChild(document.getElementById("cursorhook"));


}


out.onkeyup=findCursor;
out.onclick=findCursor;


    </script>
    </html>

Andere Tipps

Use document.activeElement. This simply returns whichever element currently has focus on the page. (MDN)

Use onfocus event which triggers whenever you are focussing an element ...

Example:

var div = document.getElementsByTagName('div');

for(var i=0;i<div.length;i++)
   div[i].addEventListener('focus',function(){document.getElementById('showRes').value = this.id;},false);

HTML :

<div contenteditable="true" id=1></div>
<div contenteditable="true" id=2></div>
<div contenteditable="true" id=3></div>
<input type="label" id="showRes"></input>

Demo Fiddle

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top