views:

187

answers:

3

I need to build a Google Suggest style drop-down box, but unfortunately am unable to use jQuery or Prototype due to various licensing restrictions. Pretty much the only thing I can use is public-domain stuff that I can modify and am not required to attribute ownership of someone else to.

In any case, I can handle the AJAX stuff fine, and the server-side scripting. Where I'm stuck is how to make Javascript respond to keyboard events:

  • Select the next item in the list when the user hits the down arrow key
  • Select and fill the text box with the selected item when they hit [Enter]
  • Close the suggest box when they hit [Esc]
  • etc. etc. etc.

Thoughts? Examples?

A: 

Not exactly what you are looking for but might be of interest. A fancy Apple.com-style search suggestion using jQuery.

Shoban
A: 

You can use this code to attach/detach events (compatible with both IE and W3C event models, so should work in all browsers):

events = {

    addEvent: function(obj, e, handler) {
     if (!obj._attachedEvents)
      obj._attachedEvents = new Array();
     if (obj._attachedEvents[e])
      this.removeEvent(obj, e);
     obj._attachedEvents[e] = handler;

     if (obj.addEventListener) 
      obj.addEventListener(e, handler, false);
     else if (obj.attachEvent) 
      obj.attachEvent('on' + e, handler);
    },

    removeEvent: function(obj, e) {
     if (!obj._attachedEvents || !obj._attachedEvents[e])
      return;

     if (obj.removeEventListener) 
      obj.removeEventListener(e, obj._attachedEvents[e], false);
     else if (obj.detachEvent) 
      obj.detachEvent('on' + e, obj._attachedEvents[e]);
     obj._attachedEvents[e] = null;
    },

    cancelEvent: function(e) {
     e = e || window.event;

     if(e.preventDefault)
      e.preventDefault();
     if(e.stopPropagation) 
      e.stopPropagation(); 
     e.cancelBubble = true;
     e.returnValue = false;
     return false;
    },

    getTarget: function(e) {
     return e.srcElement || e.target;
    }
};

and then in the handler you can see what key was pressed and do whatever action you want in response to that.

Hope it helped, Andrey

Andrey
A: 

Take a look at js-hotkeys. I've used this library in many projects. It works in all A-grade browsers which allows you to catch key-events, and the license is pretty liberal.

roosteronacid