LinuxQuestions.org
Download your favorite Linux distribution at LQ ISO.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 04-15-2016, 09:32 PM   #1
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Rep: Reputation: 61
Cool Any Javascript pro's lurking and looking for a challenge? Get element ID of caret (cursor position)?


So I'm trying to write a very minimal web editor similar to codeMirror but much simpler with way less features and portability. Rather than discuss why I'm doing this I'd rather just receive some help.

The issue I'm having right now is that I can't seem to get the caret position using Javascript.

The DIV itself contains many <spans> (every character in the editor is in it's own <span>). If possible I'd like to be able to retrieve which particular <span> the current caret is in. Either a number indicating which <span> number it's in, or better yet would be to retrieve an attribute of that <span> such as it's id.

Any tips in the right direction would be immensely appreciated.

Last edited by wh33t; 04-16-2016 at 05:02 PM.
 
Old 04-16-2016, 01:11 AM   #2
Michael Uplawski
Senior Member
 
Registered: Dec 2015
Posts: 1,620
Blog Entries: 40

Rep: Reputation: Disabled
Quote:
Originally Posted by wh33t View Post
The issue I'm having right now is that I can't seem to get the caret position using Javascript.
You talk about HTML code and an XPath problem, not a JavaScript-editor.

Could you just post the HTML in question so we could actually get an idea on the scope of your endeavour?
 
1 members found this post helpful.
Old 04-16-2016, 01:17 AM   #3
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Original Poster
Rep: Reputation: 61
Cool

Quote:
Originally Posted by Michael Uplawski View Post
You talk about HTML code and an XPath problem, not a JavaScript-editor.

Could you just post the HTML in question so we could actually get an idea on the scope of your endeavour?
Sure.

Code:
<div id="code_editor" style="white-space: pre; border:1px solid black; width:400px; height: 300px;" contenteditable="true">
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>1</span>
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>2</span>
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>3</span>
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>4</span>
</div>
Lets say the Caret is in the #4 <span>, how would I get it's position?
 
Old 04-16-2016, 02:33 AM   #4
Michael Uplawski
Senior Member
 
Registered: Dec 2015
Posts: 1,620
Blog Entries: 40

Rep: Reputation: Disabled
You get the result either with XPath or, if you can verify the element-type each time, also with DOM.

Quote:
Originally Posted by wh33t View Post
Code:
<div id="code_editor" style="white-space: pre; border:1px solid black; width:400px; height: 300px;" contenteditable="true">
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>1</span>
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>2</span>
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>3</span>
<span>L</span><span>i</span><span>n</span><span>e</span><span> </span><span>4</span>
</div>
Lets say the Caret is in the #4 <span>, how would I get it's position?
I had to look up some of it, as my xpath and java-script knowledge is rusty. These pages are helpful:
http://javascript.info/tutorial/dom
https://developer.mozilla.org/en-US/..._in_JavaScript
https://developer.mozilla.org/en-US/docs/Web/XPath

In the example, I look explicitly for the fourth item.
Code:
var element = null;
var elements = document.evaluate("//span", document, null, XPathResult.ANY_TYPE, null);
for(var i = 0; i <= 3; ++i) {
	element = elements.iterateNext();
}
alert(element.textContent);
With DOM, you will have to test for the element-type, before reading the content. In the following example, you could add a test against elements[4].nodeType or .tagName.

Code:
var elements = document.getElementById('code_editor').childNodes
alert(elements[4].textContent);
But it may be better to filter out the spans anyway and only then read the item of interest.

Last edited by Michael Uplawski; 04-16-2016 at 02:37 AM.
 
1 members found this post helpful.
Old 04-16-2016, 02:49 AM   #5
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
I am not a javascript expert by any means, but I have written my share of javascript code.

I also acknowledge your desire not to discuss why you are writing such an editor, fair enough.

But I am more than a little curious as to why you would wrap every editable character in a separate <span/> element. It seems to me that this would make every edit operation far more difficult, and many impossible (think regex or other matches).

I am not saying it is "wrong", but am very curious why it is that way, and the answer is likely to bear directly on your caret position question.

Last edited by astrogeek; 04-16-2016 at 02:53 AM. Reason: typo
 
1 members found this post helpful.
Old 04-16-2016, 03:10 AM   #6
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Original Poster
Rep: Reputation: 61
Quote:
Originally Posted by astrogeek View Post
I am not a javascript expert by any means, but I have written my share of javascript code.

I also acknowledge your desire not to discuss why you are writing such an editor, fair enough.

But I am more than a little curious as to why you would wrap every editable character in a separate <span/> element. It seems to me that this would make every edit operation far more difficult, and many impossible (think regex or other matches).

I am not saying it is "wrong", but am very curious why it is that way, and the answer is likely to bear directly on your caret position question.
The function that I am using requires I give it a node, and then a string position in that node in order to set the caret (which is required after I run my syntax_update() function which defocuses that caret out of the div).

Code:
function setCaret(node_numbe) {
    var el = document.getElementById("code_editor");
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el.childNodes[node_number],0);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}
So to simplify things I give every character it's own node, so to set the caret position I can just set it to a specific character position. Unfortunately, this is the only function I've found that works in Firefox (probably should have mentioned that earlier) that will set the caret in a contenteditablediv that has html tags embedded.

Also, I know I take a performance hit making spans everywhere but the leading webeditor is codeMirror and it's a gargantuan monster. I figure no matter what I write it should be faster than codeMirror at the cost of being way less useful.

Last edited by wh33t; 04-16-2016 at 03:15 AM.
 
1 members found this post helpful.
Old 04-16-2016, 03:12 AM   #7
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Original Poster
Rep: Reputation: 61
Quote:
Originally Posted by Michael Uplawski View Post
You get the result either with XPath or, if you can verify the element-type each time, also with DOM.


I had to look up some of it, as my xpath and java-script knowledge is rusty. These pages are helpful:
http://javascript.info/tutorial/dom
https://developer.mozilla.org/en-US/..._in_JavaScript
https://developer.mozilla.org/en-US/docs/Web/XPath

In the example, I look explicitly for the fourth item.
Code:
var element = null;
var elements = document.evaluate("//span", document, null, XPathResult.ANY_TYPE, null);
for(var i = 0; i <= 3; ++i) {
	element = elements.iterateNext();
}
alert(element.textContent);
With DOM, you will have to test for the element-type, before reading the content. In the following example, you could add a test against elements[4].nodeType or .tagName.

Code:
var elements = document.getElementById('code_editor').childNodes
alert(elements[4].textContent);
But it may be better to filter out the spans anyway and only then read the item of interest.
Awesome. I'll dig into that and try some of it out. I'm not familiar at all with XPath. Some how the caret position is part of XPath?

K, off I go to read and attempt.
 
Old 04-16-2016, 03:31 AM   #8
Michael Uplawski
Senior Member
 
Registered: Dec 2015
Posts: 1,620
Blog Entries: 40

Rep: Reputation: Disabled
Quote:
Originally Posted by wh33t View Post
So to simplify things I give every character it's own node, so to set the caret position I can just set it to a specific character position
I will not claim to understand much of that or what it should accomplish. But is there a chance that you could just simply set the caret upon iterating a string? The JavaScript String has a charAt() method.
 
1 members found this post helpful.
Old 04-16-2016, 03:38 AM   #9
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Original Poster
Rep: Reputation: 61
Quote:
Originally Posted by Michael Uplawski View Post
I will not claim to understand much of that or what it should accomplish. But is there a chance that you could just simply set the caret upon iterating a string? The JavaScript String has a charAt() method.
How might I do that? And how would I deal with duplicates words in the editor?
 
Old 04-16-2016, 03:39 AM   #10
astrogeek
Moderator
 
Registered: Oct 2008
Distribution: Slackware [64]-X.{0|1|2|37|-current} ::12<=X<=15, FreeBSD_12{.0|.1}
Posts: 6,263
Blog Entries: 24

Rep: Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194Reputation: 4194
OK, thanks for the explanation.
 
Old 04-16-2016, 03:51 AM   #11
Michael Uplawski
Senior Member
 
Registered: Dec 2015
Posts: 1,620
Blog Entries: 40

Rep: Reputation: Disabled
Quote:
Originally Posted by wh33t View Post
How might I do that? And how would I deal with duplicates words in the editor?
Now, I am at a loss, too. At one point in time, you should start developping. And that does not mean “write stuff on the computer which will do stuff”. Development means trial, error, reflection, chop firewood, get wet in the rain, come back, think again, trash your code, begin a new project, trash that, chop firewood, come back and do some random trials with code and see what ideas that may create. Development.
 
Old 04-16-2016, 03:58 AM   #12
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Original Poster
Rep: Reputation: 61
Quote:
Originally Posted by Michael Uplawski View Post
Now, I am at a loss, too. At one point in time, you should start developping. And that does not mean “write stuff on the computer which will do stuff”. Development means trial, error, reflection, chop firewood, get wet in the rain, come back, think again, trash your code, begin a new project, trash that, chop firewood, come back and do some random trials with code and see what ideas that may create. Development.
This code editor is part of a php frame work I am hoping to build. When fully done I hope to be able to edit and expand the framework by working actually inside of the webbrowser. My goal is to be completely os and software independent. I have over 300 personal work hours invested in it. This last and final piece of the frame work is the javascript editor which I have spent over 50 hours writing and re-writing over the past two weeks. It's a rather complicated thing to build as it's sort of pushing what Javascript is even capable of by working with a contentenditable div, that contains html tags inside of it to help with syntax coloring. Setting and getting the caret position is pretty straight forward I've learned if it's in a textarea, or if it's in an editable div without tags inside of it.

That's the challenge I'm having now. I have multiple posts in multiple places and most people just say "that's a really hard thing you are trying to accomplish, I'd just use codeEditor", so I thought I'd come to LQ and see if anyone had experience with it.
 
Old 04-16-2016, 04:41 AM   #13
Michael Uplawski
Senior Member
 
Registered: Dec 2015
Posts: 1,620
Blog Entries: 40

Rep: Reputation: Disabled
The scenario is getting more and more complex with each post. We outsiders cannot have the right responses for you, as long as we are not familiar with the context of your task at hand.

To iterate a string, you must have a string, first. In the scenario that we have seen in this thread, the string would be the text-node which is a child-node or “grand-child-node” of a div. You extract that one, then use the charAt() method to get the character at a numerical position.

To discern duplicate words, you must count occurrences of one and the same word and/or store them temporarily in a container of your choice. There are patterns defined for such occasions, but I have never implemented them in JavaScript. They are mostly about marking “already visited” items and you can look them up on the web. Also, I doubt that duplicate words are an issue, if the context that you have provided so far is all there is to consider. And as nothing appears to be sure and final, this may all be way too complicated and much more detailed than necessary.

Can you not just write some random HTML and get the javaScript code right prior integrating it in your project?

If not, this “tips in the right direction” - thing may be in urgent need of a foolproof definition.

I don't know, why I am thinking about that now. But I had once responded to a job-offer in Luxembourg, for an enterprise that would want to do stuff, that you do in Luxembourg, most of the time... They had this ingenuous idea of a new information platform for traders, and all the details had clearly been worked out already. All they needed now, was a developer who created it. (Darn! At that time, I had to cross half of Germany to get to the job-interview. This took some weeks to become funny.)

Last edited by Michael Uplawski; 04-16-2016 at 04:57 AM.
 
1 members found this post helpful.
Old 04-16-2016, 04:21 PM   #14
wh33t
Member
 
Registered: Oct 2003
Location: Canada
Posts: 922

Original Poster
Rep: Reputation: 61
Quote:
Originally Posted by Michael Uplawski View Post
The scenario is getting more and more complex with each post. We outsiders cannot have the right responses for you, as long as we are not familiar with the context of your task at hand.

To iterate a string, you must have a string, first. In the scenario that we have seen in this thread, the string would be the text-node which is a child-node or “grand-child-node” of a div. You extract that one, then use the charAt() method to get the character at a numerical position.

To discern duplicate words, you must count occurrences of one and the same word and/or store them temporarily in a container of your choice. There are patterns defined for such occasions, but I have never implemented them in JavaScript. They are mostly about marking “already visited” items and you can look them up on the web. Also, I doubt that duplicate words are an issue, if the context that you have provided so far is all there is to consider. And as nothing appears to be sure and final, this may all be way too complicated and much more detailed than necessary.

Can you not just write some random HTML and get the javaScript code right prior integrating it in your project?

If not, this “tips in the right direction” - thing may be in urgent need of a foolproof definition.

I don't know, why I am thinking about that now. But I had once responded to a job-offer in Luxembourg, for an enterprise that would want to do stuff, that you do in Luxembourg, most of the time... They had this ingenuous idea of a new information platform for traders, and all the details had clearly been worked out already. All they needed now, was a developer who created it. (Darn! At that time, I had to cross half of Germany to get to the job-interview. This took some weeks to become funny.)
Perhaps I wasn't transparent enough with my actual issue.

I need to know how to retrieve the caret (cursor) position from a contenteditable div that contains html tags inside of the div. I can make my through string manipulation well enough. For instance my syntax_update() function looks for specific characters contained within the element.textContent and then applies css styling around those characters, such as <? (php open tags). The tricky part is getting Javascript to give to me where exactly the cursor currently is in the div. I intentionally asked a very specific question because it's the only part I cannot seem to figure out on my own. So I was confused when you mentioned charAt as I thought you were saying charAt could somehow report to me the cursor position, which I don't believe it can, and that's why I asked how you might go about getting the cursor position from charAt.

I thank you anyways for taking a stab at the issue.
 
Old 04-16-2016, 04:42 PM   #15
ntubski
Senior Member
 
Registered: Nov 2005
Distribution: Debian, Arch
Posts: 3,780

Rep: Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081Reputation: 2081
This looks related: http://stackoverflow.com/questions/4...g-html-content
 
1 members found this post helpful.
  


Reply

Tags
caret, contenteditablediv, javascript


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
[SOLVED] Little JavaScript Challenge mzh Programming 7 08-31-2011 04:04 PM
!? element names beginning with number break javascript??? UMG:Chicken_Soüp Programming 1 01-27-2008 11:12 PM
Challenge to all Linux Geek - Suse 10.1 - Vmware Server - Xp Pro Sikooz SUSE / openSUSE 2 07-12-2007 12:44 AM
Challenge: Radeon 9600 Pro vs. TuxRacer = Choppy...? Nalorin Linux - Hardware 15 01-15-2006 07:12 PM
Discovering position of an element in JavaScript Napalm Llama Programming 4 09-07-2005 03:59 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 06:19 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration