How to move cursor to the end of WYMeditor box and set focus?

167 views Asked by At

I am using WYMEditor on my forum and users have the ability to "quote" messages of others. In such cases WYMEditor is loaded with content wrapped in blockquote tag.

Unfortunately usually the contents of the quote take more space than the input box size and when users click on the box end up entering their text inside the blockquote. This results in messy messages.

What I want is to scroll the contents of WYMEditor to the bottom, put cursor in the end and focus on the wym box. Unfortunately there is no such functionality in the WYMEditor api. There are some undocumented functions that provide selection management in the source, but my JavaScript/jQuery skills are not good enough to utilize them - I've tried but failed.

1

There are 1 answers

5
Wes Winham On BEST ANSWER

A combination of the postInit option and the jQuery scrollTop function should do the trick. I would also recommend inserting a placeholder paragraph for them along with scrolling to the bottom. For example:

jQuery('.wymeditor').wymeditor({
    postInit: function (wym) {
        var $contents,
            $p,
            $blockquote = jQuery(wym._doc).find('blockquote');
        // Insert a placeholder empty paragraph 
        // so that users will be encouraged to not type inside the blockquote
        $blockquote.after("<p>");

        // Scroll the iframe to the bottom
        $contents = $(wym._iframe).contents();
        $contents.scrollTop($contents.height());

        // Move the selection to the paragraph
        $(wym._iframe).focus();
        $p = jQuery(wym._doc).find('p');

        var sel = rangy.getIframeSelection(wym._iframe),
            range = rangy.createRange(wym._doc);

        range.setStart($p[0], 0);
        range.setEnd($p[0], 0);
        range.collapse(true);

        sel.setSingleRange(range);
        if (jQuery.browser.msie) {
            wym.saveCaret();
        }    
    }
});