[SOLVED] Any Javascript pro's lurking and looking for a challenge? Get element ID of caret (cursor position)?
ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
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.
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.
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
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.
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?
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.
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?
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.
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.
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.
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.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.