3

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;
    }
    //-----
Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
  • Have you looked at this to determine caret position? http://stackoverflow.com/questions/7745867/how-do-you-get-the-cursor-position-in-a-textarea – Rob M. Feb 23 '16 at 17:02
  • Based on the Redactor's demo, it's actually a div with `contenteditable=true`. So this might be of help: http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 – Leventix Feb 23 '16 at 17:05
  • @RobM. Ya I saw that during preliminary googling, but `console.log($('.redactor-editor').prop('selectionStart'));` is undefined. – Mike Purcell Feb 23 '16 at 17:14

1 Answers1

1

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).

rphv
  • 5,409
  • 3
  • 29
  • 47
  • You nailed it. It is indeed doing as you described. I tried using the api call of `this.selection.current().anchorOffset` but didn't work, however `document.getSelection().anchorOffset` did work. Thanks! – Mike Purcell Feb 23 '16 at 17:48