How to select a letter next to a text cursor using Javascript or jQuery?

I use jQuery and Lettering.js to wrap each letter in <h1>with span and assign it a unique identifier. I also set contenteditable=trueto <h1>, so when I click on it, I can edit the text. How would I select an element <span>that is either left or right of the cursor, so I could apply a style to it?

Here is my code

<head>

    <style media="screen" type="text/css">
        body {text-align: center}
    </style>

    <script src="scripts/jquery.js" type="text/javascript" charset="utf-8"></script>
    <script src="scripts/lettering.js" type="text/javascript" charset="utf-8"></script>

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function(){
             $("h1").lettering();
         });
    </script>

</head>

<body>

<h1 contenteditable="true" >Click me!</h1>

</body>

I would really appreciate any help or advice!

+3
source share
3 answers

In all major browsers, the following will work:

function getCaretContainerElement() {
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = sel.getRangeAt(0).commonAncestorContainer;
            return container.nodeType == 1 ? container : container.parentNode;
        }
    } else if (typeof document.selection != "undefined" &&
               document.selection.type != "Control") {
        return document.selection.createRange().parentElement();
    }
    return null;
}

var h1 = document.getElementById("foo");

h1.onkeyup = h1.onmouseup = function() {
    var caretContainerEl = getCaretContainerElement();
    if (caretContainerEl) {
        // Do stuff here
        alert(caretContainerEl.id);
    }
};

Here is a live example: http://jsfiddle.net/BATGH/1/

+2
source

, script, , . prev next , .

$(document).ready(function(){
    $("h1 p").click(function(){
        alert($(this).prev().html());
    });
});

, . http://jsfiddle.net/5n5vJ/

+1

Here's another library called Rangy that might work for you. Check out the CSSClassApplierModule add-on. This allows you to wrap the selection in a class for styling.

0
source

Source: https://habr.com/ru/post/1783960/


All Articles