Prompt html editor

by jruddell

HTML

<fieldset>
    <ledgend>Click a list item to modify the text</ledgend>
    <ul>
        <li>List item 1</li>
        <li>List item 2</li>
        <li>List item 3</li>
    </ul>
</fieldset>

CSS

fieldset { padding: 10px; border: 1px dotted #ccc; }
li {margin-left: 10px; cursor: pointer }

.prompt { position: absolute; background-color: #E0ECFF; border-radius: 3px; width: 200px; height: 50px; border: 1px solid #99C0FF }
.prompt textarea { margin: 4px 0 0 4px  }
.prompt .hint { position: absolute; bottom: 1px; left: 5px; font-size: 9px; color: #444466 }

JavaScript

function prompt(opts){
    this.opts = $.extend({}, this.defaults, opts);
    this.init();
    this.open();
}

prompt.prototype = {
    defaults: { x: 0, y: 0, text: 'Type Here' },
    init: function(){
        this.create();
        this.bind();
        this.position();
    },
    bind: function(){
        var self = this;
        this.el.click(false).find('textarea').bind('keypress', function(e){
            if(e.which === 13) self.close(e);
        });
        $(document).bind('click.prompt', $.proxy(self.close, self));
    },
    close: function(e){
        if(this.opts.close){
            this.opts.close.apply(this, arguments);
        }
        if(!e.isPropagationStopped()){
            $(document).unbind('click', this.close);
            this.el.remove();
        }
    },
    create: function(){
        this.el = $('<div class="prompt" />')
            .append('<textarea></textarea>')
                .find('textarea').val(this.opts.text)
                .end()
            .append('<span class="hint">Hint: use Shift-Enter for multiple lines</span>');
    },
    position: function(){
        this.el.css({top: this.opts.y, left: this.opts.x });
    },
    open: function(){
        this.el.appendTo('body');
        this.el.show('fast')
            .find('textarea').focus().select();  
    } 
};

$('li').click(function(){
    var li = $(this),
        pos = li.position();
    new prompt({
        text: li.html(), 
        x: pos.left, 
        y: pos.top + 17, 
        close: function(e){
            var newText = $(e.target).val();
            newText && li.html(newText);
        } 
    });
    return false;
});