473,799 Members | 3,390 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Return selectionStart for div?

I need to find a way to determine the character position of a users
selection in a div. I can do this with the following using an input
text box. Any way for a div or any text within the body tags?

<html>
<body>
<form>
<div onkeyup="s(this )" onclick="s(this )" id="myDiv">Thi s is some
text</div>
<input type="text" onkeyup="s(this )" onclick="s(this )" value="This is
some text">
</form>
<script type="text/javascript">
function s(el)
{
var sel, rng, r2, i=-1;

//firefox
if(typeof el.selectionSta rt=="number")
{
i=el.selectionS tart;
}
//ie
else if(document.sel ection && el.createTextRa nge)
{
sel=document.se lection;
if(sel)
{
r2=sel.createRa nge();
rng=el.createTe xtRange();
rng.setEndPoint ("EndToStart ", r2);
i=rng.text.leng th;
}
}
else
{
el.onkeyup=null ;
el.onclick=null ;
}
alert(i)
}
</script>
</body>
</html>

Jul 23 '05 #1
1 19019
je*********@hot mail.com wrote:
I need to find a way to determine the character position of a users
selection in a div.


The following should demonstrate some methods you can use with ranges;
tested IE6 and Mozilla 1.7.
---
<div
onmouseup="aler t(getCharPositi on(this));"
onmousedown="pr epare(this)">He llo, World</div>

<script type="text/javascript">
var getCharPosition =(function(){

function getSel(){
var sel=null;
if(
typeof document.select ion!="undefined " &&
document.select ion &&
document.select ion.type=="Text "
){
sel=document.se lection;
} else if(
window.getSelec tion &&
window.getSelec tion().rangeCou nt>0
){
sel=window.getS election();
}
return sel;
}

function createRangeFrom Sel(sel){
var rng=null;
if(sel.createRa nge) {
rng=sel.createR ange();
} else if(sel.getRange At) {
rng=sel.getRang eAt(0);
if(rng.toString ()=="") rng=null;
}
return rng;
}

return function(el){
var sel=getSel(), rng, r2, i=-1;
if(sel){
rng=createRange FromSel(sel);
if(rng){

if(rng.parentEl ement) {
if(rng.parentEl ement()==el){
r2=document.bod y.createTextRan ge();
r2.moveToElemen tText(el);
r2.collapse(tru e);
r2.setEndPoint( "EndToStart ", rng);
i=r2.text.lengt h;
}
} else {
if(
rng.startContai ner &&
rng.endContaine r &&
rng.startContai ner==rng.endCon tainer &&
rng.startContai ner==rng.common AncestorContain er &&
rng.commonAnces torContainer.pa rentNode==el
){

//make sure your DIV does not have any inner element,
//otherwise more code is required in order to filter
//text nodes and count chars

i=rng.startOffs et;
}
}
}
}
return i;
};

})();

function prepare(el){
if(el.normalize ) {
el.normalize();
}
}
</script>
---
HTH,
Yep.
Jul 23 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1431
by: DraguVaso | last post by:
Hi, For my VB.NET-application I want to indicate in a label the SelectionStart and the SelectionLength when the user selects some text in a Cell in a DataGrid. Does anybody knows in which event I can trap this, and how I can know those two values? Thanks a lot in advance,
4
2502
by: snoopy | last post by:
Hi, Previously I have this code working in FF 0.9 in a web forum : bodytext = (document.all) ? document.selection.createRange().text:document.getSelection(); if (selectedtext.createTextRange) { selectedtext.caretPos = document.selection.createRange().duplicate(); } else if (document.postform.body.setSelectionRange){ bodytext =
2
2348
by: PengYu.UT | last post by:
I have the following sample program, which can convert function object with 1 argument into function object with 2 arguments. It can also do + between function object of the same type. The last line is very long. I'm wondering if there is any way to suppress it. I can only think of typedef. But I'm not sure whether I can use typedef for the return type. Would you please help me? Please don't be daunted by the length of the code.
7
9992
by: John S | last post by:
I have an event handler tied to a text box keypress event. All I am trying to do is have it read the key and return it in upper case. Because the event doesn't return anything, I cannot use the keyword "return". I thought I could do it this way. Here is the code. public static void uCaseReturn(object sender, System.Windows.Forms.KeyPressEventArgs e){ TextBox tb = (TextBox) sender;
2
2374
by: Gary Shell | last post by:
I have a very ODD situation. I have a RichTextBox and a button. In the button click event I have the following: me.richtextbox1.SelectedText="test" Assuming I start with "aaaabbbbcccc" in the richtext box and I place the caret between the a and b and hit the button. I get "aaaatestbbbbcccc" as expected. Then I click between the b and the c and hit the button I get:
2
4563
by: marfi95 | last post by:
Hi all, I am trying to change the color of text that the user sees when they are editing a richtextbox. This is the code I am using in the TextChanged method of RichTextBox control. Dim position As Integer = rtb.SelectionStart rtb.Refresh() rtb.SelectionStart = position
1
4506
by: mosquito.dotnet | last post by:
I am getting clearly wrong values from TextBox.SelectionStart property in C# code. For example, if I move caret one character to right by pressing Keys.Right, sometimes declared SelectionStart property actually decreases, sometimes it does not change. Difference seems always at most off by 1 but it is very irritiating. My setup is as follows: Textbox txtText, txtCursor; txtText.ReadOnly = true;
1
5208
by: =?Utf-8?B?TWFyaw==?= | last post by:
Hello I've created a .NET 2.0 form and added 6 text boxes, 1 combo box and 2 button controls. The combo box has a DropDownStyle of DropDown, so the user can still type in the combo box. The combo box has the follows values in it's drop down list: "Dear Sir,"
0
1433
nicebasic
by: nicebasic | last post by:
I have used "msdxm.ocx" to embed Windows Media Player in my VB Projects. When I decided to use "wmp.dll" to embed newer version of Windows Media Player in my projects, I noticed some differences between these two objects. I realized that "wmp.dll" seems to lack "SelectionStart" and "SelectionEnd" properties. These two properties are really useful. You can play a file from any location you wish. But, I think there should be a way to do this...
0
9687
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10488
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10029
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9077
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7567
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5467
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4144
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3761
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2941
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.