Content Editable Div - Update cursor position after .html() [duplicate] - javascript

This question already has an answer here:
ContentEditable div - all HTML after the first 'x' characters
(1 answer)
Closed 6 years ago.
Using a contenteditable div, I'd like to highlight words that meet a certain criteria. One of which is if the content the user has entered has reached the allowed maximum length of that area.
I've kind of got something working - but once it reaches the threshold, the cursor position resets back to the beginning (and the user is effectively typing in reverse!).
I need this to work in IE8+.
Is there some way to get the position and set it back where it was before I replaced the contents of the area, or is my line of thinking all wrong?
Thanks
JS Fiddle:
http://jsfiddle.net/vfgLjf0c/
$(document).on("keypress", "div#editableContent", function(e) {
var element = $(this);
// KEYUP
if (e.type == "keypress") {
var curLen = element.text().length;
var maxLen = element.attr("data-maxlength");
if (curLen > maxLen) {
var overHang = element.text().substr(maxLen);
overHang = "<em style='background: #fcc;'>" + overHang + "</em>";
var newString = element.text().substr(0, maxLen) + overHang;
$(this).html(newString);
}
}
});
UPDATE Answered my own question - see below.

EDIT This issue has been resolved here by user: https://stackoverflow.com/users/2159246/alan0xd7
Solution: https://stackoverflow.com/a/31498234/1266457

Related

Firing an event when the caret gets within a particular div/span/a tag and also, when the caret leaves the tag

The idea is this -
There is a contenteditable element with some text in it. Am trying to build out a tagging mechanism (kind of like twitter's people tagging when you type '#'). Whenever a user types '#', it shows up a popover with suggestions and filters when they continue typing. Until here it's easy and I have got it figured out. The problem comes when I need to show the popover if/only if the caret is over the element containing the tag.
<div contenteditable="">
<p>Some random text before
<a href="javascript:;"
class="name-suggest"
style="color:inherit !important;text-decoration:inherit !important">#samadams</a>
Some random text after</p>
</div>
Now, whenever the user moves the caret over the a tag / clicks on it, I want to trigger an event that shows the popover, and remove it whenever the caret leaves the a tag. (kind of like focus / blur but they don't seem to work). onmousedown works but there is no way to tell if the cursor has been moved into the anchor tag with the keyboard.
Also, am doing this in angularjs, so, any solution targeted towards that would be preferable but not necessary.
Have been trying to get this to work for a day and any help is greatly appreciated.
This will let you know when your caret position is in an anchor node containing an #
$('#content').on('mouseup keydown keyup', function (event) {
var sel = getSelection();
if (sel.type === "Caret") {
var anchorNodeVal = sel.anchorNode.nodeValue;
if ( anchorNodeVal.indexOf('#') >= 0) {
$('#pop').show()
} else {
$('#pop').hide()
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content" contenteditable="">
<p>Some random text before
<a href="javascript:;"
class="name-suggest"
style="color:inherit !important;text-decoration:inherit !important">#samadams</a>
Some random text after</p>
</div>
<div id="pop" style="display:none">Twitter node found</div>
You could add some regex to further validate the selection.
There is a weird move with RegExps and offset calculation in the code below, but let me explain why it's a better solution.
I've been building a complicated editor using contenteditable about a year ago. It wasn't just a disaster. It was a fucking disaster. There is no cover-all-the-cases spec. Browsers behave differently in every possible detail and it changes frequently. Put a caret before # char and you will get this is Gecko:
<a href="#">|#name
And this in WebKit:
|<a href="#">#name
Well, unless <a> is paragraph's first child. Then result would be the same as in Gecko. Try to put caret after the nickname and both will tell it's inside the link. Start typing, and caret will pop out the element - a year ago Gecko wasn't doing it.
I've used native Selection & Range APIs in this example, they are IE9+. You may want to use Rangy instead.
$el = $('#content');
var showTip = function (nickname) {
// ...
console.log('Show: ' + nickname);
};
var dismissTip = function () {
// ...
console.log('Hide');
};
// I'm sure there is a better RegExp for this :)
var nicknameRegexp = /(^|\b|\s)\#(\w+)(\s|\b|$)/g;
var trackSelection = function () {
var selection = window.getSelection(),
range = selection.rangeCount > 0 ? selection.getRangeAt(0) : null;
if (range == null || $el[0].contains(range.commonAncestorContainer) == false) {
return dismissTip();
}
var comparer = range.cloneRange();
comparer.setStart($el[0], 0);
var offset = comparer.toString().length;
var match, from, to;
while (match = nicknameRegexp.exec($el[0].textContent)) {
from = match.index + match[1].length;
to = match.index + match[1].length + match[2].length + 1;
if (offset >= from && offset <= to) {
// Force rewind, otherwise next time result might be incorrect
nicknameRegexp.lastIndex = 0;
return showTip(match[2]);
}
}
return dismissTip();
};
$el.on({
// `mousedown` can happen outside #content
'mousedown': function (e) {
$(document).one('mouseup', function (e) {
// Calling function without a tiny delay will lead to a wrong selection info
setTimeout(trackSelection, 5);
});
},
'keyup': trackSelection
});
Just looked at Fire event when caret enters span element which led me here, pretending your case was quite similar except finding if current word is specifically beginning with # for the modal to show...
The thing you need is a way to get the word we're on at the moment we move or type, then check the first character and hide/show the modal pane accordingly will be pretty easy.
function getSelectedWord(grab=document.getSelection()) {
var i = grab.focusOffset, node = grab.focusNode, // find cursor
text = node.data || node.innerText, // get focus-node text
a = text.substr(0, i), p = text.substr(i); // split on caret
return a.split(/\s/).pop() + p.split(/\s/)[0]} // cut-out at spaces
Now you can listen for keydown or selectionchange events and show your pane knowning what have already been written of the current/selected word.
editor.addEventListener('keydown', ev => {
if (ev.key.substr(0, 5) != 'Arrow') // react when we move caret or
if (ev.key != '#') return; // react when we type an '#' or quit
var word = getSelectedWord(); // <-- checking value
if (word[0] == '#') showModal(word.substr(1)); // pass without '#'
});
Note that social networks and code completion usually stops at caret position while I did check for word tail... You can go usual by removing p off of getSelectedWord function definition if desired.
Hope this still helps; Happy coding ! ;)

Create a child div accordingly if another child already exists at that location (x,y)

I am inserting a textarea to a side bar (exactly on the right to), wherever a click is made on the page. The code is:
$('#page_to_be_clicked').click(function(e){
var offset = $(this).offset();
var comment_box_y_coord = e.pageY - offset.top;
alert(comment_box_y_coord);
$("#sidebar").append('<textarea id="cmmnt" rows="4" cols="10" '+
'style="position:absolute;top:'+comment_box_y_coord +
'px;left:5px"></textarea>');
})
The problem with this is that, if a textarea is already present at the location, it will overlap the existing, i.e. if a click is made twice at the same point on the page, then two textareas are created on top of each other. Instead, it should be created one below the other.
Is there a way to check, if a child already exists at the required co-ordinates?
Any help will be appreciated. Thanks.
How exactly should the textareas appear on clicks in a sequence:
This needs to be tested properly, but I think you need to do this:
DEMO
In your function change this line:
var comment_box_y_coord = checkCoords(e.pageY - offset.top);
and then add this function:
function checkCoords(y) {
if ($("textarea").length>0) {
$ts = $("textarea");
for (var i = 0; i<$ts.length;i++) {
var $ti = $ts.eq(i),
tcoords = [$ti.offset().top, $ti.offset().top+$ti.height()]
if (y>=tcoords[0] && y <= tcoords[1]) {
y = tcoords[1]+3;
}
}
}
return y;
}

Making "next" button work

I am creating a simple numeracy game where by there is a grid populated with numbers. The numbers are hidden and when the game is run the grid space is highlighted. A div on the side produces a sum to help the user get the correct answer. The user then clicks the corresponding numbers that animate into position and signal whether they are right or wrong.
I have but in a next button ('.minibutton'), so that if the user gets the answer wrong 3 times they have a chance to move to the next question. The button also has a .trigger('click') function so that when a word is completed correctly it moves on automatically and keeps the game flowing.
My problem is the button has stopped working and I am clueless as to why. Here is the ".minibutton" function...
$('.minibutton').click(function() {
var sum = $('#answerlist li[data-answer="' + answer + '"]').data('sum');
$(right).val('');
$(wrong).val('');
$('td').removeClass('spellanswer');
score.wrong = 0;
var r = rndanswer;
while (r == rndanswer) {
rndanswer = Math.floor(Math.random() * (listOfanswers.length));
}
when I added this statement the button stopped working
//for (var x = 0; x < listOfanswers.length; x++) {
//if (eval(sum.replace("=", "").replace("x", "*")) == listOfanswers[x].name) {
// rndanswer = x;
// }
//}
$('td[data-answer="' + listOfanswers[rndanswer].name + '"]').addClass('spellanswer');
$('td[data-answer=' + answer + ']').removeClass('answerglow').removeClass('answerglow4').removeClass('answerglow3').css('color', 'transparent');
var noExist = $('td[data-answer=' + listOfanswers[rndanswer].name + ']').hasClass('answerglow2');
if (noExist) {
$('.minibutton').prop('disabled', false);
} else {
$('.sumstyle').text(sum);
sum.hide();
}
}).trigger("click");
http://jsfiddle.net/ZAfVZ/28/
Running the jsFiddle gives this error:
Object 1 + 2 = has no method 'hide'
You're trying to hide a string, which is obviously wrong. It's causing the script to stop executing after that point. Remove/comment out sum.hide(), and the 'next' button appears after three wrong guesses.
I've edited the JSFiddle to define sum (a text string containing the sum that the player is trying to answer) and seumElem (the HTML element containing the sum) at the top of the function: http://jsfiddle.net/ZAfVZ/30/

Find caret position in textarea in pixels [duplicate]

This question already has answers here:
How do I get the (x, y) pixel coordinates of the caret in text boxes?
(2 answers)
Closed 8 years ago.
I was wondering if it is possible to find the exact location of the caret inside a textarea in pixels in relation to the entire page. For instance, if I have typed This is text into my text box, I would like to know the pixels from the top left of the screen to the caret.
It would be in the form X: 200 Y: 100. This is so I can position a floating div. This needs to be done dynamically in javascript.
Thanks guys
This "raw code" works at least in IE.
Using the code you can put your <TEXTAREA> where ever you want in page, and the <DIV id="db"> will follow it. Even despite of the scrolling position of the page. You can fix the position of <DIV> by changing the literal numbers at d.style...6-statements.
<body>
<div id="db" style="position:absolute;left:-20px;top:-20px;border:1px solid red;">V</div>
<br><br><br>
<form id="props">
<textarea id="ta" style="width:200px;height:100px;" onkeyup="moveDiv();"></textarea>
</form>
<script>
<!--
var b=document.body;
var d=document.getElementById('db');
var a=document.getElementById('ta');
function moveDiv(){
var sel=document.selection;
var targ=sel.createRange();
d.style.top=a.offsetTop+a.clientTop-d.clientHeight-6;
d.style.left=targ.offsetLeft+b.scrollLeft-6;
return;
}
// -->
</script>
</body>
Positioning of the <DIV> is not quite exact, but gets better when using fixed-width font in <TEXTAREA>.
Here is a simple mix of ideas from Caret position in pixels in an input type text (not a textarea) , Caret position in textarea, in characters from the start and document.getElementById vs jQuery $() to get the caret position in jQuery for an <input> element. It works when clicking inside it, but not when moving the caret using the arrows or typing.
<input id="someid">
<span id="faux" style="display:none"></span><br/>
<script>
var inputter = $('#someid')[0];
var faux = $('#faux');
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$("#someid").click( function( event ) {
caretpos = getCaret(inputter);
calcfaux = faux.text($(this).val().substring(0, caretpos));
fauxpos = calcfaux.outerWidth();
$("#getpx").text(fauxpos + " px");
});
</script>
Instead of var inputter = document.getElementById('someid') we use var inputter = $('#someid')[0];
Here is a FIDDLE.

JavaScript 'contenteditable' -- Getting/Setting Caret Position

I have read a few posts on positioning the caret, but none seem to answer my particular issue.
I have 2 divs (div1 and div2)
div1 = noneditable div
div2 = contenteditable div
both divs contain exact same contents
when user clicks on div1, it gets hidden, and div2 appears in exact location and user can edit
The problem: I want the caret to appear in exact location on div2 as div1
So, I need some way to READ the location where the user clicks on div1, and then when div2 appears place the cursor/caret in that same location, so a getCaretLocation(in_div_id) and setCaretLocation(in_div_id) set of functions.
Any way to do that?
Thanks -
Short answer : You can't
Long answer : The problem you'll face is that you'll be able to get (x,y) coordinates for the click event on div1, but any implementation of the caret position while require you knowing the position of the caret in the content (which is the number of characters preceding the caret).
To convert the (x,y) coordinates to a character position you actually need to know how many characters were before (ie. left on the current line and above, if the text is ltr).
If you use a fixed width font, you can simplify the problem : mapping an (x,y) coordinate to a (line, column) coordinate on a character grid.
However, you still face the problem of not knowing how the text is wrapped. For example :
------------------
|Lorem ipsum |
|dolor sit amet |
|consectetur |
|adipiscing elit |
------------------
If the user clicks on the d in dolor, you know that the character is the 1st on the 2nd line, but without knowing the wrapping algorithm there is no way you'll know that it is the 13th character in "Lorem ipsum dolor sit…". And there is no guarantee that such a wrapping algorithm is identical across browsers and platform.
Now, what I'm wondering is why would you use 2 different synced div in the first place ? Wouldn't it be easier to use only one div and set its content to editable when the user clicks (or hovers) ?
You could insert a tiny span-element at the caret, get its position, and remove it. For a cross-browser range and selection library, see rangy.
you can, basically you need set temporary content editable on your first div to catch caret pos
$('div1').hover(function()
{ $(this).attr('contenteditable','true');
},function()
{ $(this).removeAttr('contenteditable');
}).mouseup(function()
{ var t = $(this);
// get caret position and remove content editable
var caret = t.getCaret();
t.removeAttr('contenteditable');
// do your div switch stuff
...
// and apply saved caret position
$('div2').setCaret(caret);
});
now just need get/set caret method :)
edit > here is my own, (live demo)
getSelection:function($e)
{ if(undefined === window.getSelection) return false;
var range = window.getSelection().getRangeAt(0);
function getTreeOffset($root,$node)
{ if($node.parents($root).length === 0) return false; // is node child of root ?
var tree = [], treesize = 0;
while(1)
{ if($node.is($root)) break;
var index, $parent = $node.parent();
index = $parent.contents().index($node);
if(index !== -1) { tree[treesize++] = index; } $node = $parent;
}; return tree.reverse();
}
var start = getTreeOffset($e,$(range.startContainer));
var end = getTreeOffset($e,$(range.endContainer));
if(start & end === false) return false;
return {start:start,end:end,startOffset:range.startOffset,endOffset:range.endOffset};
}, setSelection:function($e,s,win)
{ $e.focus(); if(s === false) return; var sel = win.getSelection(); sel.removeAllRanges();
function getNode($e,s)
{ var node = $e;
for( var n=0;n<s.length;n++ )
{ var index = s[n]; if(index < 0) break;
node = node.contents(':eq('+index+')');
} return node.get(0);
}
var start = getNode($e,s.start), end = getNode($e,s.end), range = win.document.createRange();
range.setStart(start,s.startOffset); range.setEnd(end,s.endOffset); sel.addRange(range);
}
It sounds like you are trying to do an inline edit... have you looked at the jeditable plugin?
When you click on an element, a Selection object with zero length is created (get it from element.getSelection() , where element is the div in question). The focusOffset of that object will let you know that you clicked on, for example, the 74th character in that div (this is the thing that Adrien said was impossible in a different answer).

Categories