Search code examples
javascriptjqueryredactor

jQuery - contenteditable - Determine if caret before or after an image


I am having to debug a vendor api (Redactor wysiwyg) and had a question, is it possible to determine if the caret is before or after an image?

When an image is inserted it results in this markup:

<figure>
    <img src='/ur/face.png' />
    <figcaption>Ur face</figcaption>
</figure>

I am trying to make so that if the caret is before the image, and the user presses enter, the image (entire figure block) gets moved down so user can add information above the image, vs if the caret is after the image, the caret skips the figcaption (entire figure block) and creates a new paragraph after the image so user can add stuff after the image.

Right now, if caret is before image, a "p" block is inserted within "figure" and if caret is after image, a "p" block is inserted after image, but before "figcaption", which results in a trainwreck, especially on mobile.

------ Update ------

If you stumble across this with the same issue, this patch will work (v2.1.2.2):

onEnter: function(e)
{
    ....

    //-----
    // !!!!! HACK !!!!!
    //-----
    /*
    // figure
    else if (this.keydown.figure)
    {
        setTimeout($.proxy(function()
        {
            this.keydown.replaceToParagraph('FIGURE');

        }, this), 1);
    }
    */

    else if (this.keydown.figure)
    {
        var node = $(this.opts.emptyHtml);

        //  If after image (1), then we will insert after image
        if (1 === document.getSelection().anchorOffset) {

            $(this.keydown.figure).after(node);
        }

        // If before image (0), lets insert before image so users can move images down
        else {

            $(this.keydown.figure).before(node);
        }

        this.caret.start(node);

        return false;
    }
    //-----

Solution

  • Can you use document.getSelection().anchorOffset?

    In testing with the Redactor demo, this value is 0 if the carat is before the image and 1 if it's after the image (assuming the carat is inside the <image> tag in both cases).