TextboxList: Fancy Facebook-Like dynamic inputs!

TextboxList Screenshot

Check out a demo of TextboxList before reading!

While working on my big and exciting new project, I decided to include an input that resembles the famous Apple Mail to: textfield. I’d seen it in Facebook before, which has a really decent implementation of this concept (it work well, but it doesn’t respect any modern programming principles; basically, it’s a big tag soup with lots of inline Javascript)

I created my own, MooTools 1.2 compatible, in just 5kb. It’s not only small, but also really frexible! Here are some notes of the creation process and how to implement it in your own projects.

Anatomy of the control

As usual, I try to come up with a semantic, unobstrusive approach. I start with the CSS and the markup that will be my end result.

I want to go from something like this:

Click here to see HTML code

  1. <li id="facebook-list" class="input-text">
  2. <label>FacebookList input</label>
  3. <input type="text" value="" id="input-demo2" />
  4. </li>

to something like this (only one possible scenario, naturally)

Click here to see HTML code

  1. <li id="facebook-list" class="input-text">
  2. <label>FacebookList input</label>
  3. <ul class="holder">
  4. <li class="bit-input"><input type="text" value="" class="smallinput" /></li>
  5. <li class="bit-box">Jorge Luis Borges <a href="#" class="closebutton"></a></li>
  6. <li class="bit-input"><input type="text" value="" class="smallinput" /></li>
  7. <li class="bit-box">Julio Cortazar <a href="#" class="closebutton"></a></li>
  8. <li class="bit-input"><input type="text" value="" class="maininput" /></li>
  9. </ul>
  10. </li>

Basically, it’s a group of pieces (that I’ll call bits), that can be either a box or an input (small, except for the main one). The user is able to move around between the bits by using his keyboard or his mouse.

Javascript

As far as the javascript goes, I try to first think about reusable code (usually classes) that I may use. I thus first coded the class that adds resizing capabilities to the small fields as the user types, and a small utility method to find the caret position.

The only challenges I found was handling the complex events while keeping everything crossbrowser. Again, none of this would have been possible if it wasn’t for MooTools (1.2).

Using it

All you have to do is:

Click here to see Javascript code

  1. new TextboxList('input-demo');

Where input-demo is the id of the desired input to replace

The constructor can take these options:

  • onInputFocus (event, fired when an input gets focus)
  • onInputBlur (event, fired when an input loses focus)
  • onBoxFocus (event, fired when a box gets focus)
  • onBoxBlur (event, fired when a box loses focus)
  • onBoxDispose (event, fired when a box is removed)
  • resizable (option, hash, passed to ResizableTextbox constructor)
  • className (option, string, prefix of the classnames of the generated objects)
  • extrainputs (option, boolean, adds small inputs between boxes if true)
  • startinput (option, boolean, adds a small input before the first box if true)
  • hideempty (option, boolean, hides the small inputs by default)

Extending it

One of the my favorite features of MooTools is how easily you can create and extend classes. It makes you feel in a truly Object-Oriented environment, overcoming all Javascript limitations and complexities to handle functionalities like this by default.

I decided that, for the sake of simplicity, the class would not incorporate stuff like boxes removal through clicks, or even autocompletion (like Facebook does), since the scenarios to use this control are multiple and diverse.

Here is an example of how easily you can add the small remove links next to the name (and some CSS, of course)

Click here to see Javascript code

  1. var FacebookList = new Class({
  2.  
  3. Extends: TextboxList,
  4.  
  5. createBox: function(text, options) {
  6. var li = arguments.callee.parent(text, options);
  7. li.addEvents({
  8. 'mouseenter': function() { this.addClass('bit-hover') },
  9. 'mouseleave': function() { this.removeClass('bit-hover') }
  10. });
  11. li.adopt(new Element('a', {
  12. 'href': '#',
  13. 'class': 'closebutton',
  14. 'events': {
  15. 'click': function(e) {
  16. new Event(e).stop();
  17. if(! this.current) this.focus(this.maininput);
  18. this.dispose(li);
  19. }.bind(this)
  20. }
  21. }));
  22. return li;
  23. }
  24.  
  25. });

Changelog

  • 0.1: initial release
  • 0.2: code cleanup, small blur/focus fixes

Download

Click here to download a zip file containing examples, TextboxList documented (8kb) and compressed (5kb)

New! TextboxList with autocompletion

23 Responses to “TextboxList: Fancy Facebook-Like dynamic inputs!”

  1. 1
    Boris Says:

    Nice script ! Congrats’ !

  2. 2
    Davis Says:

    Sweet!!!

  3. 3
    Devthought - Guillermo Rauch’s Blog » TextboxList meets Autocompletion Says:

    [...] my previous blogpost I explained how to extend TextboxList to add closing functionality via a link added to [...]

  4. 4
    Ihsan Kriato Says:

    Great code for the great Mootools library :)

  5. 5
    TextboxList + Autocomplete | Infected-FX| tutoriales, recursos y referencias para desarroladores y diseñadores web Says:

    [...] salió a la luz “TextboxList: Fancy Facebook-Like dynamic inputs!” se trata de una forma bastante “original” de mostrar / editar listas. No [...]

  6. 6
    Richard Says:

    Fantastic!! mootools too I love it :)

  7. 7
    Daniel Buchner Says:

    Any chance I could get a port of the script for Moo 1.1, the project I am currently working on was going to use some 1.2 scripts but the compatibility package on Moo’s site wasn’t compatibilizing :) the way it should in many cases. Pleaseeeee!!!!

    Thanks a mil!

  8. 8
    Guillermo Rauch Says:

    @Daniel
    I don’t plan on supporting 1.11. However, it shouldn’t be hard to do it yourself.

  9. 9
    mediodia Says:

    He llegado gracias al blog de Anieto2k…Me ha parecido un gran trabajo el tuyo, pero para ser la primera vez que me acerco al mundo mootols, me pierdo bastante a la hora de hacer una cosa muy basica para poder importar tu script a mi herramienta…

    ¿Crees sencillo que pudiera implementar un autocomplete dinamico haciendo llamadas al servidor si el patron de busqueda no aparece en el primer fichero cargado?

    A la hora de hacer submit del formulario, bajo que “name” aparecen los elementos que se añaden? Supongo que existe la manera de poder pasar el contenido el “text” de los nodos por debajo de class=”feed” al text cuyo id es “facebook-demo” , pero no consigo ver el modo…

    Saludos y gracias de todos modos por tu esfuerzo

  10. 10
    Matt Says:

    Hi there,

    json.html is a static file and is giving me a 405 error under IIS 5.x as the POST method is not allowed for text/html by default.

    If I change the extension to json.asp and alter the file name to json.asp in test.js it works OK.

    …. is this an acceptable workaround or should I reconfigure IIS ?

    { Thanks Guillermo for a great library ]

  11. 11
    Guillermo Rauch Says:

    Matt
    Whatever URL data comes from is fine! json.html is only intended as an example.

  12. 12
    Mootools - 40 przykładowych zastosowań | Ptaszor i jego blog! Lol... Says:

    [...] Auto uzupełnianie listy w polu tekstowym (mootools) [...]

  13. 13
    Real Estate Postcards Dude Says:

    Right on! And good job keeping the code clean too.

  14. 14
    TextboxList: Fancy Facebook-Like dynamic inputs! Now, in Prototype | InteRiders Says:

    [...] everybody, after coming across Guillermo Rauch’s script, I knew i had to port it into my favorite library, Prototype. In this page you will find the [...]

  15. 15
    Software Development Company Says:

    Great work, what if I want to make it with single select?

  16. 16
    Chaffe Says:

    Greetings, I wrote a class to extend the TextBoxList class, and I’m in need to run some function onBoxDispose. I uncommented the onBoxDispose: $empty, option in the TextBoxList class and wrote a function in my new class onBoxDispose: function(){//mystuff}, but for some reasons, it’s not getting run when the box is disposed. what am I missing here? Thanks.

  17. 17
    Chaffe Says:

    Guillermo, any word of advice on the question above?

  18. 18
    TextboxList: Fancy Facebook-Like dynamic inputs! | Techspectacular.com - Diving & Oceanic Says:

    [...] (more…) [...]

  19. 19
    Will Says:

    the TextboxList is very cool~!

  20. 20
    jason Says:

    tested and works a treat! thanks

  21. 21
    Kim Steinhaug Says:

    Really cool! It does however throw some errors in IE7 when testing the demo, some small try catch would solve it I know, just wanted to mention it. As Im sitting on a developer machine with script debugger on the forced error popup really gets you, :D

    Great work!

  22. 22
    MooTools Script Sammlung | astBlog Says:

    [...] http://devthought.com/textboxlist-fancy-facebook-like-dynamic-inputs/ bzw.  http://devthought.com/textboxlist-meets-autocompletion/ Lizenz: MIT [...]

  23. 23
    100 Scripts and Script Resources | OpenJason Says:

    [...] Devthought - Guillermo Rauch’s Blog » TextboxList: Fancy Facebook-Like dynamic inputs! [...]

Leave a Reply