Gallaxhar
Gallaxhar

Reputation: 1036

jQuery keyboard activate a button

this is what I got so far

http://jsfiddle.net/qEKfg/

It's two buttons that activate on click and look like keyboard keys.
I'm trying to make it where they will only activate (animate) on a keyboard press of the related keys (CTRL and D) This will make an 'animated buttons' effect for bookmarking my website, because CTRL+D is the hotkey to bookmark a page.

But I don't know how to set it up to work with keyboard keys in html or jQuery
if some could help I would be really REALLY grateful

Upvotes: 1

Views: 900

Answers (2)

Daedalus
Daedalus

Reputation: 7722

The following should work for you. However, note that due to the window losing focus, I've added in a timer to release the on-screen 'buttons' after 5 seconds, as the window losing focus at that specific time prevents the keyup event from firing.

$(document).ready(function() {
    var keys = [];
    $(window).on('keydown keyup', function(e) {
        if (e.type == "keydown") {
            if (e.keyCode == 17 || e.keyCode == 91) {
                $("a.a_demo_two:contains('CTRL')").addClass("active");
                keys[0] = e.keyCode;
            }
            else if (e.keyCode == 68) {
                $("a.a_demo_two:contains('D')").addClass("active");
                keys[1] = 68;
            };
            if ((keys[0] == 17 || e.keyCode == 91) && keys[1] == 68) {
                setTimeout(function() {
                    $('a.a_demo_two').removeClass("active");
                }, 5000);
            }
        }
        else {
            if (e.keyCode == 17 || e.keyCode == 91) {
                $("a.a_demo_two:contains('CTRL')").removeClass("active");
            }
            else if (e.keyCode == 68) {
                $("a.a_demo_two:contains('D')").removeClass("active");
            }
            keys = [];
        }
    });
});​

DEMO

Upvotes: 2

vittore
vittore

Reputation: 17589

Basically you just put handler on keydown and keyup events and trigger whatever you want. Something like that

$('body').on('keydown', function(e) {   
   console.log(e)    
   if (e.ctrlKey) $('.a_demo_two').trigger('mousedown')
   if (e.keyCode === 100) $('.a_demo_two').trigger('mousedown')       
});

$('body').on('keyup', function(e) {
   console.log(e)    
   if (e.ctrlKey) $('.a_demo_two').trigger('mouseup')
   if (e.keyCode === 100) $('.a_demo_two').trigger('mouseup')       
});

Upvotes: 0

Related Questions