Page 1 of 1

Keyboard shortcuts with javascript

Posted: Sun Nov 12, 2006 12:15 pm
by adamb10
Is there a way to show/hide a table with a keyboard shortcut using javascript?

Posted: Sun Nov 12, 2006 12:27 pm
by aaronhall
onKeyPress event and window.event.keyCode

Posted: Sun Nov 12, 2006 12:30 pm
by adamb10
Ok. I dont really know much(if any) javascript. :P

Posted: Sun Nov 12, 2006 12:30 pm
by Chris Corbyn
You may actually be able to do something with the accesskey attribute too.

I've used the actual event capturing stuff before now though by reading the ascii value stored in keypressEvent.keyCode.

Posted: Sun Nov 12, 2006 12:37 pm
by Chris Corbyn
adamb10 wrote:Ok. I dont really know much(if any) javascript. :P

Code: Select all

function readKey(e)
{
    if (e.keyCode == 46) alert('Delete pressed!');
}

if (document.captureEvents) document.captureEvents(Event.KEYDOWN);
document.onkeydown = readKey;

Posted: Sun Nov 12, 2006 12:45 pm
by adamb10
ok, and what do I put in the table tag? Readkey?

Posted: Sun Nov 12, 2006 1:04 pm
by Chris Corbyn
adamb10 wrote:ok, and what do I put in the table tag? Readkey?
No, let's say you wanted the "h" key to toggle the table display.

Code: Select all

function toggleTable(e)
{
    e = e || window.event;
    
    if (e.keyCode == 72) //Key code for h
    {
        var tableElement = document.getElementById('my_table');
        if (tableElement.style.display == 'block') tableElement.style.display = 'none';
        else tableElement.style.display = 'block';
    }
}

if (document.captureEvents) document.captureEvents(Event.KEYDOWN);
document.onkeydown = toggleTable;

Code: Select all

<table id="my_table" ... >

Posted: Sun Nov 12, 2006 1:15 pm
by adamb10
Thanks. That appeared to have worked. It does have a few bugs though. When you press h, the table gets skinny then pressing h again makes it go away. Pressing h again makes the table skinny.

http://adamb10.com/pb2/

Thanks!

Posted: Sun Nov 12, 2006 5:06 pm
by jayshields

Code: Select all

function toggleTable(e)
{
    e = e || window.event;
   
    if (e.keyCode == 72) //Key code for h
    {
        var tableElement = document.getElementById('my_table');
        if (tableElement.style.display == '') tableElement.style.display = 'none';
        else tableElement.style.display = '';
    }
}

if (document.captureEvents) document.captureEvents(Event.KEYDOWN);
document.onkeydown = toggleTable;
Might work