ichord / caret.js Goto Github PK
View Code? Open in Web Editor NEWGet caret postion and offset from text field
Home Page: http://ichord.github.com/Caret.js
License: MIT License
Get caret postion and offset from text field
Home Page: http://ichord.github.com/Caret.js
License: MIT License
It may take a long time....
Hello!
I have a textarea with font-size=14px, line-height=20px and padding=40px.
When I try to get top position of any character, I get 40 (padding) + linesBefore*20 + 2px
.
Here is a fiddle with demo: http://jsfiddle.net/gkalabin/aeHNj/
The output is
A position is {"left":40,"top":42,"height":16}
B position is {"left":40,"top":62,"height":16}
G position is {"left":40,"top":162,"height":16}
What are these 2 extra pixels? How can I get rid of them?
Also, If you change font-size then the extra can vary from -1 (18px) to 3 (12px)
Hey there,
I've got an issue using the cursor position where it's incredibly wrong. I typed in the following
123456789 123456789
My cursor was at the end and it said it was at 33
The format of my code is a contentEditable div with a
inside so I can create line numbers using the :before psuedoelementIs there a reason why the cursor position is so wrong?
Thanks!
something like this
Know how to solve this problem now, but no IE browsers yet.
Let me find an Windows first..= =
$("#inputor").caret("offset", 50);
$("#inputor").caret("position");
$("#inputor").caret("position", 12);
First of all, awesome job. At.js worked amazingly; I really appreciate all your work!
I did find one small bug:
http://ichord.github.io/Caret.js/
Try typing out a sentence then add "&", for example. It should be easy enough to fix by converting &
to &
before writing it to the DOM.
Thanks again!
Is there an easy way how to make Caret.js + At.js work with CodeMirror or any other code editor? It doesn't seem they are contenteditable based.
Caret.js works by creating a mirror of the textarea as a div and copies the CSS of the textarea.
In our application, we had CSS rules that is applying positioning on span's that Caret.js creates in the mirror div.
This causes caret.js to miscalculates the position of the caret. I will try to come up with a simple test case that illustrates the issue.
Another problem with caret when I use it inside a CKEditor.
The caret method return the right value when caret is located anywhere in the editable zone except at the beginning of the lines (at the left side of the zone. In that case, the method return null.
The bug can be reproduced on the online demo :
http://ichord.github.io/Caret.js/
Best regards
Nemo
I've recently started using Caret.js in order to use atWho.js. I'm using it on a rails app and have installed it two ways. First using the jquery-atwho-rails gem, and then manually installing caret.js and atwho.js. Both times I'm getting the following error:
TypeError: $dom[0] is undefined
oDocument = $dom[0].ownerDocument;
It's happening here specifically on line 366:
configure = function($dom, settings) {
var error, iframe;
if ($.isPlainObject(settings) && (iframe = settings.iframe)) {
$dom.data('caret-iframe', iframe);
return setContextBy(iframe);
} else if (iframe = $dom.data('caret-iframe')) {
return setContextBy(iframe);
} else {
oDocument = $dom[0].ownerDocument;
oWindow = oDocument.defaultView || oDocument.parentWindow;
try {
return oFrame = oWindow.frameElement;
} catch (_error) {
error = _error;
}
}
};
Not sure what's causing that or how to fix it, any suggestions?
Hi,
I've tried to use Caret on a textarea but it seems there's a bug in the calculation of the caret offset under Firefox and IE (it works fine under Chrome).
Tested versions : IE 11 and Firefox 28 under Windows
Firefox 32.0.3 under Linux
You can see the problem with the Caret demo
http://ichord.github.io/Caret.js/
Any ideas...
Best regards
Nemo
你好,感谢你的工作。
我使用Caret.js控制caret,在input 和 textarea里一切正常,在div里使用caret('pos', num)不能正常工作。
另外一个小问题是同样在div里,输入第一个字符时就不能使用caret('offset')获得caret的position,接着输入就没有问题。
不知道我说清楚了没有,谢谢。
在 content editable div 中
Could you add version number of the script in copyright header like in At.js
Thank you
Hi.
I have a problem when entering the Korean and Japanese characters in kontenteditavle.
The symbols are repeated if you press the arrow keys or space. You can will see on the page with a demonstration script
Got a "Uncaught TypeError: Cannot read property 'left' of undefined" on line 86 of jquery.caret.js.
The page URL is : http://ichord.github.io/Caret.js/
The error occurs when i switch from the Textarea input to the contentEditable input.
Currently, Caret only fully supports textareas, because of a difference in input vs textarea. The biggest time you see this problem is when you type past the visible end of a text field (so your text scrolls left/right). Because of the expectation for it to behave like a textarea, the position calculations get thrown way off.
There probably needs to be a special code-path for text fields, where width is not applied to the mirror span's CSS, and it's treated as being "infinitely wide". From a quick test where width is just not applied, that seems to improve position detection.
Are there any plans for a .destroy() method that removes all events and elements created by Caret.js?
Please make library available as bower package
If someone will ned - I've used for contenteditable :
EditableCaret.prototype.setPos = function(pos) {
var inputor, range;
inputor = this.domInputor;
if ( oDocument.getSelection ) {
var selection = oDocument.getSelection(), node;
range = selection.getRangeAt( 0 );
var getNode = function ( node ) {
if ( node.childNodes.length > 0 ) {
for ( var i = 0; i < node.childNodes.length; i++ ) {
var childNode = getNode( node.childNodes[i] );
if ( length < pos )
continue;
return childNode;
}
} else if( node.nodeType === 3 ) {
length += node.nodeValue.length;
if( pos <= length && $( node ).closest( '*[contenteditable]' ).attr('contenteditable') == 'false' ){
pos += ( length - pos )+1;
}
return node;
}
}
if ( inputor.childNodes.length > 0 ) {
var length = 0;
for ( var i = 0; i < inputor.childNodes.length; i++ ) {
node = getNode( inputor.childNodes[i] );
if ( length < pos )
continue;
break;
}
if ( length < pos ) {
range.setEnd( node, node.nodeValue.length );
}
else {
range.setEnd( node, pos - length + node.nodeValue.length );
}
} else {
range.setEnd( inputor, Math.min( pos, inputor.nodeValue.length ) );
}
range.collapse( false );
selection.removeAllRanges();
selection.addRange( range );
} else if ( inputor.setSelectionRange ) {
inputor.setSelectionRange( pos, pos );
}
return inputor;
};
In http://ichord.github.io/Caret.js/ example, in the iframe editor, if we type more text so that an scroll bar appears, the position is not correct when scroll is at bottom.
The check in jquery.caret.js#293 is done by doing
if (pos) {
...
}
So if pos is 0 it doesn't work, the check should be
if ( pos && pos !== 0) {
...
}
When using on a div with contenteditable
, putting the cursor at the end of the content, then hitting enter a few times doesn't update the top caret position correctly.
your At.js plugin provides the minified files in a dist/
folder. It would be great if you could do the same for caret.js (previously, I was not caring about it as jquery.atwho.js was including caret in the minified file)
when mouseenter the iframe there's an error: SCRIPT5022: WrongDocumentError file: jquery.caret.js,line: 105,column: 13 in IE9-11
There seems to be a bug when clicking directly before the first character in a ContentEditable element. After the click, the ContentEditable cursor disappears and a rogue character is inserted into the editor.
I think this has to do with trying to detach the shadow cursor in EditableCaret.prototype.getOffset method.
I'm trying to debug it and will roll in a patch if I can figure it out... just thought I'd add it as an issue here in case it's an easy fix that I'm missing.
How does Caret.js compare with the textarea-caret-position library in Component?
Not talking about the ID, but the word in the README:
Get caret postion or offset from inputor
Does it mean text area + input type="text", or other input elements (contenteditable)?
https://www.npmjs.com/package/jquery.caret
PS Thank you for your work!
Seriously, I spent days trying to find the best solution to this problem, and you've just probably saved me another few weeks of bug fixing and tedious code.
Thank you for sharing your hard work, you're awesome :)
Hello!
Here is a screenshot (there is no line breaks in textarea's content, the text is wrapped by the browser itself):
The problem is that you copy to mirror div just a substring(0, caretPos).
In case of the caret in long word (0123456789 in the screenshot) you will copy some part of the word (012). So in case of textarea the word is wrapped (there is no room for 0123456789), but in case of the mirror there is space for 012.
I'm trying to get this module to work with Browserify but I'm failing to extend jQuery with the error Uncaught TypeError: $(...).caret is not a function
. Here's my code:
global.jQuery = require "jquery"
require "jquery.caret" # package.json -> "browser": { "jquery.caret": "./node_modules/jquery.caret/dist/jquery.caret.js" }
$ ->
console.log $("div").caret("position")
Where am I going wrong?
Does someone have a d.ts file of this library?
In the http://ichord.github.io/Caret.js/ example, in the textarea, if we select a text, when we do click to unselect the text by placing the cursor inside the selection bounds, the cursor will have a new position but the info box will not be updated.
Do you have any plans in releasing version of Caret.js that will not be dependent on jQuery?
Could caret used for manipulating selected Text in a contentEditable element?
Get / set range, replace / insert text, start and end position?
Might be worth noting that it's probably IE9+ only, given the use of getBoundingClientRect
's width. https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
# 你是需要比较endContainer和domInputor是否相等但是编译结果却不是
range.endContainer is not @domInputor
# -> range.endContainer === !this.domInputor
range.endContainer isnt @domInputor
# -> range.endContainer !== this.domInputor
see https://github.com/ichord/Caret.js/blob/master/src/jquery.caret.coffee#L81
see https://github.com/ichord/Caret.js/blob/master/src/jquery.caret.js#L129
see http://coffeescript.org/#operators
I am getting an error when using this in IE. The error goes away if I qualify $inputor as this.$inputor, as below, but it doesn't put the box in the correct place.
Caret.prototype.getIEOffset = function(pos) {
var h, range, x, y;
range = this.domInputor.createTextRange();
if (pos) {
range.move('character', pos);
}
x = range.boundingLeft + this.$inputor.scrollLeft();
y = range.boundingTop + $(window).scrollTop() + this.$inputor.scrollTop();
h = range.boundingHeight;
return {
left: x,
top: y,
height: h
};
};
The Library doesn't work if the input (or contenteditable) is inside a shadow root since window.getSelection
doesn't work there (shadow_root.getSelection
would be the right method to be called)
Many of the files in the VCS repository are actually build artefacts: the JavaScript library is evidently generated from a CoffeScript source, for example.
Please document which files are mechanically generated, and the full procedure for generating them from source. The goal is to describe what a recipient needs to do to build from (maybe customised) source, the same way the maintainers do it.
Hi!
Simple demo on jsFiddle like this http://jsfiddle.net/gkalabin/LcCEw/ does't work in IE10:
SCRIPT5: Access is denied.
jquery.caret.js, line 133 character 9
Is it possible to use caret.js without jQuery. jQuery should be optional, not everyone uses jQuery.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.