Forum Moderators: open
Say there is a webpage of 15 lines and there is a world "How" on line 12.I selected HOW.Now i want to know cordinates of H or HOW itself.I know javascript support cordinates but was wondering whether it would work for me.?
my 2nd question is that does cordinate changes according to screen resolution?
If it's just one word in particular, you could place that word in a span element and then find the position of that.
Even this gets a tad involved as it may be inside a whole nest of elements, that themselves may have offsets within the page themselves.
This would work:
In your HTML you would have something like
<span id="howSpan">How </span>
Then in your javascript you could find that span thus:
function findMyHowThing()
{
var obj=document.getElementById("howSpan");
var curleft = obj.offsetLeft;
var curtop=obj.offsetTop;
while(obj.offsetParent)
{curleft=curleft + (obj.offsetParent.offsetLeft);
curtop=curtop + (obj.offsetParent.offsetTop);
obj=obj.offsetParent;
}
alert("your span was found at " + curleft +":" + curtop);
}
Elegant it isn't but doubt you'll find anytning simpler and reliable.
Oh and BTW. If you want to use those co-ordinates to move something over them, don't forget to add the "px" to the end of each of them.
1) IE only (using the "DHTML Model"). Actually, something similar may be possible using standard DOM in Moz & Opera, but if so, the actual objects and methods will be different.
2) This one uses the offset properties of the textRange [msdn.microsoft.com] object. So getting the absolute position will involve some recursion ala texmex's post above.
var tRange = document.selection.createTextRange();
alert(tRange.offsetLeft)
I did find this
http://www.xulplanet.com/references/objref/Selection.html#method_extend
and then this
http://developer.mozilla.org/en/docs/DOM:range.startOffset#Example
for mozilla browsers but kinda unsure how to test in my script.
[quirksmode.org...]
My html is given below:
[codes]
<body>
<div>
This is a text.my Name is Adan
</div>
<a href="javascript:getSel();">getRange</a>
<a href="javascript:txtDeSelection();">getRange2</a>
</body>
[/codes]
The same page returning Selection on IE
bold text is very bold,it should be less bold
O! bold text where art thou?
and if i select "bold" in second line,startOffset doesnt tell the actual position of the starting of word rather it calculates it for each line.
Is there anyway or i would have to use charat() stuff to find the exact position?
Thanks
It does talk about startContainer and startoffset.But i am unsure and didnt get any example either that how these two can be used with each other.Forinstance,I have code:
<p>Hello World</p>
<hi>Hi you</h1>
and If i select "o" in "you",i am not sure how to get its actual position.
Please guide me in this regard.