Reputation: 779
I have three contenteditable
divs 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?
Upvotes: 1
Views: 1542
Reputation: 779
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>
Upvotes: 3
Reputation: 5018
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>
Upvotes: 2