Search code examples
javascriptcodemirror

codemirror for just one-line-textfield?


I have a one line textfield. (input type='text')

I don't have a textarea.

This textfield allows the user to enter small strings in a simple DSL. To give you an idea they look like this:

  • from milan to london
  • from italy(rome,florence) to uk

I was thinking to replace this textfield with codemirror

my questions are:

  • is using code mirror for one line textarea a good idea ?
  • has anybody done this ?
  • are there any other approaches to make a textfield more 'colourful' ?

Thanks,


Solution

  • Well, there is a way to make a single-line editor using rich capabilities of CodeMirror. First, you'll have to add a full-featured CodeMirror object (use a textarea).

    Assume you've got var cm = CodeMirror(...). (Use value: ""). Then do

    cm.setSize(200, cm.defaultTextHeight() + 2 * 4);
    // 200 is the preferable width of text field in pixels,
    // 4 is default CM padding (which depends on the theme you're using)
    
    // now disallow adding newlines in the following simple way
    cm.on("beforeChange", function(instance, change) {
        var newtext = change.text.join("").replace(/\n/g, ""); // remove ALL \n !
        change.update(change.from, change.to, [newtext]);
        return true;
    });
    
    // and then hide ugly horizontal scrollbar
    cm.on("change", function(instance, change) {
        $(".CodeMirror-hscrollbar").css('display', 'none');
        // (!) this code is using jQuery and the selector is quite imperfect if
        // you're using more than one CodeMirror on your page. you're free to
        // change it appealing to your page structure.
    });
    
    // the following line fixes a bug I've encountered in CodeMirror 3.1
    $(".CodeMirror-scroll").css('overflow', 'hidden');
    // jQuery again! be careful with selector or move this to .css file
    

    This works just fine for me.