0

So, i have this code which is appending Tab when tab is pressed, but the cursor stays behind the tab after the tab is appended. How to make it when i append the new element the cursor to moves after/in right of the tab. I have this code: jQuery

$('.example').each(function(){
    this.contentEditable = true;
});

if(event.keyCode==9){
    event.preventDefault();
    $('.example').append('\t');
}

HTML

<div class="example"></div>

This is the code that is not working from har0lds proposal(which from what i read in the topic that he given is not what i asked):

$('.example').each(function(){
    this.contentEditable = true;
});

function placeCaret(field){
                var editable = field,
                selection, range;

                // Populates selection and range variables
                var captureSelection = function(e) {
                // Don't capture selection outside editable region
                var isOrContainsAnchor = false,
                    isOrContainsFocus = false,
                    sel = window.getSelection(),
                    parentAnchor = sel.anchorNode,
                    parentFocus = sel.focusNode;

                while(parentAnchor && parentAnchor != document.documentElement) {
                    if(parentAnchor == editable) {
                    isOrContainsAnchor = true;
                    }
                    parentAnchor = parentAnchor.parentNode;
                }

                while(parentFocus && parentFocus != document.documentElement) {
                    if(parentFocus == editable) {
                    isOrContainsFocus = true;
                    }
                    parentFocus = parentFocus.parentNode;
                }

                if(!isOrContainsAnchor || !isOrContainsFocus) {
                    return;
                }

                selection = window.getSelection();

                // Get range (standards)
                if(selection.getRangeAt !== undefined) {
                    range = selection.getRangeAt(0);

                // Get range (Safari 2)
                } else if(
                    document.createRange &&
                    selection.anchorNode &&
                    selection.anchorOffset &&
                    selection.focusNode &&
                    selection.focusOffset
                ) {
                    range = document.createRange();
                    range.setStart(selection.anchorNode, selection.anchorOffset);
                    range.setEnd(selection.focusNode, selection.focusOffset);
                } else {
                    // Failure here, not handled by the rest of the script.
                    // Probably IE or some older browser
                }
                };

                // Recalculate selection while typing
                editable.onkeyup = captureSelection;

                // Recalculate selection after clicking/drag-selecting
                editable.onmousedown = function(e) {
                editable.className = editable.className + ' selecting';
                };
                document.onmouseup = function(e) {
                if(editable.className.match(/\sselecting(\s|$)/)) {
                    editable.className = editable.className.replace(/ selecting(\s|$)/, '');
                    captureSelection();
                }
                };

                editable.onblur = function(e) {
                var cursorStart = document.createElement('span'),
                    collapsed = !!range.collapsed;

                cursorStart.id = 'cursorStart';
                cursorStart.appendChild(document.createTextNode('—'));

                // Insert beginning cursor marker
                range.insertNode(cursorStart);

                // Insert end cursor marker if any text is selected
                if(!collapsed) {
                    var cursorEnd = document.createElement('span');
                    cursorEnd.id = 'cursorEnd';
                    range.collapse();
                    range.insertNode(cursorEnd);
                }
                };

                // Add callbacks to afterFocus to be called after cursor is replaced
                // if you like, this would be useful for styling buttons and so on
                var afterFocus = [];
                editable.onfocus = function(e) {
                // Slight delay will avoid the initial selection
                // (at start or of contents depending on browser) being mistaken
                setTimeout(function() {
                    var cursorStart = document.getElementById('cursorStart'),
                    cursorEnd = document.getElementById('cursorEnd');

                    // Don't do anything if user is creating a new selection
                    if(editable.className.match(/\sselecting(\s|$)/)) {
                    if(cursorStart) {
                        cursorStart.parentNode.removeChild(cursorStart);
                    }
                    if(cursorEnd) {
                        cursorEnd.parentNode.removeChild(cursorEnd);
                    }
                    } else if(cursorStart) {
                    captureSelection();
                    var range = document.createRange();

                    if(cursorEnd) {
                        range.setStartAfter(cursorStart);
                        range.setEndBefore(cursorEnd);

                        // Delete cursor markers
                        cursorStart.parentNode.removeChild(cursorStart);
                        cursorEnd.parentNode.removeChild(cursorEnd);

                        // Select range
                        selection.removeAllRanges();
                        selection.addRange(range);
                    } else {
                        range.selectNode(cursorStart);

                        // Select range
                        selection.removeAllRanges();
                        selection.addRange(range);

                        // Delete cursor marker
                        document.execCommand('delete', false, null);
                    }
                    }

                    // Call callbacks here
                    for(var i = 0; i < afterFocus.length; i++) {
                    afterFocus[i]();
                    }
                    afterFocus = [];

                    // Register selection again
                    captureSelection();
                }, 10);
                };
}

if(event.keyCode==9){
    event.preventDefault();
    $('.example').append('\t');
    var element = document.getElementsByClassName('example');
    placeCaret(element[0]);
}

The solution is this - Set caret position right after the inserted element in a contentEditable div

Community
  • 1
  • 1
emanuilov
  • 122
  • 1
  • 10
  • 1
    See http://stackoverflow.com/questions/1181700/set-cursor-position-on-contenteditable-div – Michael Coxon Sep 10 '14 at 15:59
  • First that is when the user click somewhere other than the editable div to save the location, not for that i asked and second it doesn't work. I tried it this way - function which wants var field and set editable = field, for field i use var element = document.getElementsByClassName('example'); moveAfterNewElement(element[0]) and when i click tab the tab even stopped to appear. I don't have any errors in the console. – emanuilov Sep 10 '14 at 16:15
  • Fair enough but please list what you have tried in your question to avoid it being mistaken as duplicate. – Michael Coxon Sep 10 '14 at 16:17
  • I tried some things but all of them were to move the cursor to the end of the editable div some were to set location, i think that clear enough explained what i am trying to do. It is not duplicate because there is/or i just can't found any topic like this. I will post the code of that you told me to try in a few seconds. – emanuilov Sep 10 '14 at 16:22
  • Well to be honest, you haven't really fully explained what you are trying to do. As a guess I would conject that you are possibly trying to insert a tab when the tab key is pressed on the keyboard. If this is the case I would suggest writing that in the question. There may be other ways of achieving what you are trying to do without jQuery. It would help others get to a solution for you if you explained the code in natural language first. – Michael Coxon Sep 10 '14 at 16:28
  • 1
    I thnik, that now is fully clear what i am trying to acheive. – emanuilov Sep 10 '14 at 16:32
  • After a short Google there is a SO post about inserting a tab in a content editable I have come up with this: http://webdevrefinery.com/forums/topic/6509-insert-a-tab-in-a-contenteditable-div/?p=61194 – Michael Coxon Sep 10 '14 at 16:40
  • When i tap TAB it tabs the whole row, not just adds tab. And again that is not what i asked for. – emanuilov Sep 10 '14 at 16:47

0 Answers0