开发者

Responsive Rich Editor Preview

Consider this Example.

The essential bit is the JavaScript:

function encodeInput(editor) {
    theText = editor.val();
    theText = theText.replace(/\*\*\*(.*?)\*\*\*/, '<strong><i>$1</i></strong>', 'g');
    theText = theText.replace(/\*\*(.*?)\*\*/, '<strong>$1</strong>', 'g');
   开发者_开发百科 theText = theText.replace(/\*(.*?)\*/, '<i>$1</i>', 'g');
    console.log(theText);
    $('#preview').html(theText);
}

$(function() {
    $editor = $('#editor');
    $editor.keyup(function() {
        encodeInput($(this));
    });
});

Tested and works great (I do need the \*\*\* part or it doesn't work).

Anyways, on to the main course

The Problem

Because I'm using keyup, the script is not very responsive (eg. it only "runs" once the user had let go of the key). I want it to behave more like the editor here on StackOverflow, where the key is pressed and response occurs immidiately.

I tried using keydown and keypress but it seems as if the val() attribute is not updated when it runs, so I can't really know the updated value.

In Short

How can I make it more responsive, so that when the user pressed a key, the preview is automatically updated??


You can use the HTML5 input event in most browsers and the propertychange event in IE < 9. These events fire immediately after the textarea's value is updated.

Here's an updated demo using these events:

http://jsfiddle.net/muWm2/1/

I've written about this in a few places on SO. Here are two of them:

  • Catch only keypresses that change input?
  • jQuery keyboard events

I would recommend against updating the preview on every single change to the textarea's value because it could quickly get unresponsive, which is a big no-no for user experience. I'd suggest "debouncing" the event, in this case waiting for a period of user inactivity (say half a second) before updating the preview. Here's an answer and a link that may help:

  • How to trigger an onkeyup event that's delayed until a user pauses their typing?
  • Debouncing Javascript Methods by John Hann


You can bind() both the keyup and keydown events:

$editor.bind('keyup keydown', function() {
    encodeInput($(this));
});

I noticed that only the first occurrence was working, adding the g flag to the regex seemed to help, and for the purpose of the jsfiddle demo only, unchecking "normalize css" made the bold text appear.

http://jsfiddle.net/tuUym/3/


Keypress fires when the key is pressed continously, so you have to bind it to keypress in order to see the result. And thats it.

http://jsfiddle.net/tuUym/4/

UPDATE: I see what you mean. Maybe you need an input poller? Check out the de obfuscated wmd code. That will help you achieve the lagless editor you aim for:

WMD Download

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜