View Full Version : Consume shift / ctrl if used on multiple select?

02-15-2009, 05:55 PM
I'm trying to do something like google suggest on the Danbooru API (http://danbooru.donmai.us/help/api) in GreaseMonkey (https://addons.mozilla.org/en-US/firefox/addon/748)
I got the suggestions popping up part working fine for which I used an absolute positioned select multiple.

Is there any way to consume the shift/ctrl keypress event so things like ctrl + click and shift + arrow down etc just select ONE choice?
Removing the 'multiple' atrribute would do me no good as it changes the select to a combobox instead of a list.

(I realize this could be done via other elements, but select multiple seems to good to pass on as it already does highlighting / has good keyboard accessibility and doesn't need any CSS for overflow-y etc)

Well as it probably has to tie in with the on enter key I got so far I might as well post the code

var srch = document.createElement( 'input' );

var tagList = document.createElement( 'select' );
tagList.id = 'tagList';
tagList.multiple = true;
tagList.addEventListener( 'keypress', function( e ) {
if( e.which == 13 ) //If enter is pressed (selection is made)
//Well this is odd, no way to return multiple select values? workaround time..
var str = '';
for( var i = 0; i < e.target.options.length; i++ )
if( e.target.options[i].selected )
str += e.target.options[i].textContent;
srch.value = str;
}, false );

Well.. looks like I can consume the entire event with e.preventdefault. Not what I want though, any way to consume only the shift and or crtl key event while leaving other keys unharmed?

02-18-2009, 05:22 PM
okay, looks I'll be going with a work around.. monitor all the key events on the window.
If shift is pressed I've a way to detect it then.. and can handle accordingly.

For those trying to archieve something similar, I recommend adding the following bit of code to your script so you can monitor what's going on:

var tstBox = document.createElement( 'pre' );
tstBox.style.position = 'absolute';
tstBox.style.top = 0;
tstBox.style.backgroundColor = 'yellow';
document.body.appendChild( tstBox );

document.addEventListener( 'keydown', function( e ) {
tstBox.textContent = e.type+"\n";
tstBox.textContent += e.which;
}, false );
document.addEventListener( 'click', function( e ) {
tstBox.textContent += "\n"+e.type+"\n";
tstBox.textContent += e.which;
}, false );
document.addEventListener( 'keyup', function( e ) {
tstBox.textContent = '';
}, false );

02-19-2009, 06:25 AM
Um, you do not need to use multiple. You can set <select size="10"> to get it to show a bunch of options.