Git Product home page Git Product logo

jwerty's Introduction

No Longer Actively Maintained

If someone would like to take over maintainence, feel free to get in touch (@keithamus on twitter). I'll happily transfer this over.

Awesome handling of keyboard events

Gitter

NPM Downloads Release Gittip donate button

Sponsor

jwerty is a JS lib which allows you to bind, fire and assert key combination strings against elements and events. It normalises the poor std api into something easy to use and clear.

jwerty is a small library, weighing in at around 1.5kb bytes minified and gzipped (~3kb minified). jwerty has no dependencies, but is compatible with jQuery, Zepto, Ender or CanJS if you include those packages alongside it. You can install jwerty via npm (for use with Ender) or Bower.

For detailed docs, please read the README-DETAILED.md file.

The Short version

Use jwerty.key to bind your callback to a key combo (global shortcuts)

jwerty.key('ctrl+shift+P', function () { [...] });
jwerty.key('⌃+⇧+P', function () { [...] });

Specify optional keys:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] });

or key sequences:

jwerty.key('↑,↑,↓,↓,←,→,←,→,B,A,↩', function () { [...] });

You can also (since 0.3) specify regex-like ranges:

jwerty.key('ctrl+[a-c]', function () { [...] }); // fires for ctrl+a,ctrl+b or ctrl+c

Pass in a context to bind your callback:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this);

Pass in a selector to bind a shortcut local to that element:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this, '#myinput');

Pass in a selector's context, similar to jQuery's $('selector', 'scope'):

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, this, 'input.email', '#myForm');

If you're binding to a selector and don't need the context, you can ommit it:

jwerty.key('⌃+⇧+P/⌘+⇧+P', function () { [...] }, 'input.email', '#myForm');

Calls to jwerty.key return a subscription handle that you can use to disconnect the callback

var h = jwerty.key('ctrl+shift+P', function () { [...] })
h.unbind()

Use jwerty.event as a decorator, to bind events your own way:

$('#myinput').bind('keydown', jwerty.event('⌃+⇧+P/⌘+⇧+P', function () { [...] }));

Use jwerty.is to check a keyCombo against a keyboard event:

function (event) {
    if ( jwerty.is('⌃+⇧+P', event) ) {
        [...]
    }
}

Or use jwerty.fire to send keyboard events to other places:

jwerty.fire('enter', 'input:first-child', '#myForm');

jwerty's People

Contributors

amcdnl avatar brihogan avatar gitter-badger avatar keithamus avatar kossnocorp avatar lennym avatar loicmahieu avatar luishdez avatar luto avatar makoconstruct avatar scream avatar spatmole avatar sukrosono avatar timoschilling avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jwerty's Issues

Unbinding should be internalized

Referring to issue #19, returning an unbindable object creates enormous complexity in the client. We now have to internalize jwerty subscriptions in, say, an array or a dictionary.

The better approach would simply be this:

jwerty.unbind('tab', _context);

Internally, jwerty would handle the unbind.

I have written three keyboard navigators with the following class hierarchy:

KeyboardNavigator

KeyboardMatrixNavigator

KeyboardCalendarNavigator

In the matrix navigator, I simply wish to remap up and down to #prevRow and #nextRow, respectively. But I can't really do that without a whole lot of management machinery of the jwerty subscriptions.

In the #bindKeys method of KeyboardMatrixNavigator, where I override the #bindKeys method in KeyboardNavigator, I should simply be able to do this:

KeyboardNavigator.prototype.bindKeys.call(this);
jwerty.unbind('up', _context);
jwerty.key('up', ...)
jwerty.unbind('down', _context);
jwerty.key('down', ...)

Your thoughts?

Modified keys not working in a sequence set

First off, thanks for an awesome library!

I can't seem to get the the sequence functionality working with modified keys (e.g. space,shift+3). Is there a way around this? In other words, I want a user to press the space bar and then the pound key. Ideally it'd be able to do space,#, but space,shift+3 is ok, too.

I've tested space,3 and shift+3 and both work separately (of course), but I can't get space,shift+3 (or the ideal space,#) working.

Add a timeout in combination before the execution

Let say i have to hotkeys:

  • shift+c
  • shift+c,t

Today, both handlers are executed when i press shift+c,t

It can be usefull to add a timeout after shift+c to check if there is not another key that is coming.

Semicolon not a recognized character

I noticed I can't get the semicolon character to work.
I added this to line 121, and it seems to work just fine. Any reason not to add it to your code?

        // semicolon
        ';':186, semicolon:186,

document using + sign

is it possible to use + as the trigger key or not because it's a special glue character for jwerty commands?

Trying to do something like this ctrl+shift++

Key combo triggers on single key.

Shouldn't this only trigger when both 'w' and 'e' are pressed?
It triggers when 'w' is pressed.

jwerty.key('w+e', function () { console.log('w+e') });

Numbers binding

Hi,

I'm evaluating your library for keyboard navigation in my project. I really
like the concept but I have some difficulties with number keys.

I want to bind numbers, from 0 to 9, so I started with this :

jwerty.key('[0-9]', function (e) {
    alert(e.which);
}); 

It didn't work for me because I have an azerty keyboard and I obtain '0' by pressing 'shift+0'
(http://www.computerhope.com/help/azerty.gif). This leads to :

jwerty.key('shift+[0-9]', function (e) {
    alert(e.which);
}); 

Works great, but I don't care if the numbers come from the numpad or the left of the keyboard.
I have to handle all of them the same way. So I tried this :

// does not work
jwerty.key('shift+[0-9],num-[0-9]', function (e) {
    alert(e.which);
});
// does not work
jwerty.key('shift+[0-9],num-0,num-1,num-2,num-3,...', function (e) {
    alert(e.which);
})

and finally this :

jwerty.key('shift+[0-9]', function (e) {
    alert(e.which);
});
jwerty.key('num-0', function (e) {
    alert(e.which);
});
jwerty.key('num-1', function (e) {
    alert(e.which);
});
.
.
.
jwerty.key('num-9', function (e) {
    alert(e.which);
});

The last code works, but is not as easy as promising :)

I think the more inuitive way of handling numbers would be the first solution : '[0-9]'.
In my case, I don't need the distinction between numpad and normal keyboard (do some people really need that?).

What do you think?

Best regards
Olivier

jwerty.key(...) returns nothing

To reproduce the issue install jwerty with bower.
bowert install jwerty

You can use -F key (force last version) to solve the issue.
bowert install jwerty -F

I can solve the issue if I download zip and install from local folder. But then I have a warning about critical dependencies, as I use webpack.

IE 8 issue when binding to enter key in textboxes

We use jwerty for handling enter key in textboxes. Works great in all browsers except for IE 8. When using jwerty to handle enter key in IE8 texbox, the default behavior is not prevented and causes an undesired form post to happen.

This is correctable in v.3 via the following jwerty.js code:

is: function (jwertyCode, event, i /? 0/) {
jwertyCode = new JwertyCode(jwertyCode);
// Default i to 0
i = i || 0;
// We are only interesting in i of jwertyCode;
jwertyCode = jwertyCode[i];
// jQuery stores the real event in originalEvent, which we use
// because it does annoything stuff to metaKey
event = event.originalEvent || event;

        //!!!!!!!!!Modification for IE 8 support!!!!!!!!!  Thanks be to ninja master Teddy for finding this!!!
        event.metaKey = event.metaKey || false;

Enable distinguishing of casing

Well, imagine you have a binding like "Q", and "q" - both of them are fired by hitting "Q" key on your keyboard.

But if you somehow display these keys on the screen of your app - users type shift+q to match the uppercase "Q", and just q for lowercase "q".

Hence, it would be nice if jwerty could detect shift+key, if bound key IS IN uppercase.

jwerty fails to run in "strict" mode

Setting "strict" mode enabled brakes jwerty, since it has some very small, non-valid approaches - global assignments, duplicate declarations etc. Should be very easy to fix.

Firing actually doesn't do anything in latest Chrome?

JSBin

<!doctype html>
<html lang="en-US">

<head>
<script src="https://rawgit.com/keithamus/jwerty/master/jwerty.js"></script>
</head>

<body>

<form id="myform">
  <input type="text">
  <textarea>
  aa
  bb
  </textarea>
</form>  

<script>
jwerty.fire('a', 'input', '#myForm');
jwerty.fire('ctrl+a', 'textarea');
</script>

</body>
</html>

After loading the page, I don't see an a in the input, or the textarea contents selected.

Does fire only trigger bound events? If so, that should be mentioned in the docs.

Better support for mapping multiple keys

Is there a way to retrieve THE key pressed in case of single key? Because I'm not sure I wouldn't interfere with jwerty events, I'm trying to use jwerty for all my keys management. In which case, it happens I need to get the key pressed. How can I? I can do "if jwerty.is('x')", but it can be tedious.

Keyboard shortcut to launch modal window...

0 down vote favorite

I am uing your link for integrating keyboard short cuts.. It redirects to the given URL after pressing the key..

jwerty.key('f2', function () {
window.location = document.getElementById('SaleLink').href;
});

I am using following code to launch the bootstrap modal window :

[a href=PopUp.php?Id=1 data-toggle="modal" data-target="#myModal">Open</a]

$('#myModal').modal({ show: false});
$('#myModal').on('hidden', function () {
    console.log('modal is closed');
})
$("a[data-toggle=modal]").click(function (e) {
lv_target = $(this).attr('data-target');
lv_url = $(this).attr('href');
$(lv_target).load(lv_url);
}); 

It works fine when i click on the link...i am trying to add this code to launch the modal window when i press a key say f2 ...since it redirects directly to the given URL therefore the modal window is not opening....Can you please suggest any solution for this??

Unbind doesn't work.

I suddenly discovered that unbind functionality doesn't work.

My code looks like that:

var k = jwerty.key('↑/↓/←/→/pgdown/pgup/home/end', callback);
...
k.unbind(); // actually, k is undefined because jwerty.key returns nothing

I tried to google the issue, but nobody complains...

There is not an unbind function

Hi, i'm using this pluggin, it's really good. I need to create and remove dynamic shortcuts, so i need an unbind function. I think it's a good idea to extend jwerty with this functionality.
I have implemented a jwert.unbind function that unbinds all the events related to a key code. It works fine, but just for jquery.

If some want i can share the code. And if anyone has done a similar function I'd like to see it to compare with my code.

Thanks!

Difference between source code and archives/npmjs versions

Hey !
I encounter an issue with your (great !) library.
When i install jwerty using npm, it download me a file with :

(function (global, exports) {
...
}(this, ...));

This doesn't work with my project, because the global isn't set to window
But when i'm looking to your source code, i see :

(function (global, exports) {
...
}(typeof global !== 'undefined' && global.window || this, ...));

which works well.
Can you explain me why there is a difference between these two (same ?) files ?
Thank you in advance =)

Problem with jwerty.fire

Hello Keith,

I am not able to get jwerty.fire working. Could you please help me with this simple example?

Thanks in advance.

Regards

Stephan

<!DOCTYPE html>
<html>
<head>
  <style>
button { margin:10px; }
div { color:blue; font-weight:bold; }
span { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script src="jwerty.js"></script>
</head>
<body>
  <button>Button #1</button>
<button>Button #2</button>
<div><span>0</span> button #1 clicks.</div>
<div><span>0</span> button #2 clicks.</div>
<script>
$("button:first").click(function () {
update($("span:first"));
});
$("button:last").click(function () {
//$("button:first").trigger('click');

jwerty.fire('enter', 'button:first');

update($("span:last"));
});

function update(j) {
var n = parseInt(j.text(), 10);
j.text(n + 1);
}
</script>

</body>
</html>

Bugs with some symbols (OSX)

There is a bug with detecting some symbols such as parentheses and hyphens.
For example i've got "½" instead of "-" or "9" and "0" instead of "(" and ")".
But if with parentheses i can understand the logic (shift + 0 is opening bracket), then the logic of "½" is very confusing.

Please push latest version to npm

The version that is currently on npm is leaking globals ($f and n) but the updated version in github has that problem fixed. Can you please update the version in npm?

Ender dependencies

Hi,

Im using jwerty with Ender. I installed jwerty using:

ender build jwerty

but it doesn't install the dependencies (based on my tests they are bean and qwery).

Key binding not working on IE

Hi,

First of all gratz for this awesome lib !
Nevertheless i cant make it work on internet explorer due to the event.metaKey property which is 'undefined' on IE.
Thus each property in the jwertyCode object are not equals to those in the event object :

// For each property in the jwertyCode object, compare to `event`
for (var p in jwertyCode[n]) {
// ...except for jwertyCode.jwertyCombo...
 if (p !== 'jwertyCombo' && event[p] !== jwertyCode[n][p]) returnValue = false;
 }

I temporarily bypassed this IE problem by removing the metaKey references in your lib.

fire f11

Hi,

I am trying to get a full screen mode. i.e firing f11 on body load.

I am using the below code

jwerty.fire('{122}');

//Below is the full code hope this will help you to run it..

<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jwerty.js"></script> <script> $(function() { //alert('Test7'); jwerty.fire('{122}'); //keycode for F11 function key }); </script>

I look forward to hear from you.

Thanks & Regards
Ganesh K

Typo on the website

I believe

Use jwerty.event as a decorator, to bind events your own way:

$('#myinput').bind('keydown', .event

should be

Use jwerty.event as a decorator, to bind events your own way:

$('#myinput').bind('keydown', jwerty.event

Trying to use same letter ('a' and 'ctrl+a')

Hi,

I'm trying to assign a shortcut to "a" key, it's working so good.

I also want to assign a shortcut to "ctrl+a" but it doesn't work with the other shortcut.
I think it's a conflict problem and I couldn't figure it out.

Ex:

        jwerty.key('a', function () {
            alert('pressed a key");
        });
        jwerty.key('ctrl+a', function () {
            alert('pressed ctrl+a key');
        });

Thanks.

Forward slash does not work

I want to make forward slash do something, but since it is used as a divider it does not work. Output is:

Uncaught TypeError: Cannot read property 'length' of null

When I do this:

jwerty.key('/', function()
{
   console.log('test');
});

TypeError: jwertyCode is null

I am using jwerty for menu short-cuts in my MVC project. But getting error, as follows.

TypeError: jwertyCode is null

what could be the issue?

jwerty.is() not working in FF

// For each property in the jwertyCode object, compare to `event`
for (var p in jwertyCode[n]) {
    // ...except for jwertyCode.jwertyCombo...
    if (p !== 'jwertyCombo' && event[p] != jwertyCode[n][p]) returnValue = false;
}

I'm trying to check for key binding when clicking on an element but jwerty.is() does return false for 'shift', 'cmd' & 'alt'. After some minutes of debugging I've found the problem: You're getting the originalEvent which is in that case [object MouseEvent] and has no property keyCode for that reason. Therefore the result is always false. I'm not sure if there is a solution for this problem in FF, but it is working fine in Chrome.
Thanks for this wonderful library!

Unbind key will not work

Hi there!

I have a modal popup which shows a error message. At the bottom of this popup there is a button to close the popup and do some other things.
I'd like to close the popup while pressing enter and setting the focus to the button will not work.

So I have decided to use jwerty for this and I have the following binding:

jwerty.key('enter', function () { $("#btnClose2").click(); });

It works fine. But after the popup is closed the primary behaviour regarding pressing event should be restored so I'd like to unbind this immediately after the click on btnClose2 has occured.

I tried the two following possible solutions:
1)

jwerty.key('enter', function () {
    $("#btnClose2").click();
    $(window).off('keydown.jwerty');
});

Alternatively, jwerty.event will return a function which, when run, unbinds the event, so:

var unbind;
$(document).on('keydown', (unbind = jwery.event('enter', function () {
     $("#btnClose2").click();
     unbind();
}))); 

In both cases the unbinding will not work.

Please give me a hint how to solve this.

Many thanks for your help
Carsten

jwerty.fire

Hi,

First of all thanks for the wonderful work.. I'm not able to get jwerty.fire to work.. In fact, im quite not understand the way it is supposed to work.. Pls see the sample below,

<pre>
<form id="myForm" name="myForm" method="post" action="/">
Go to google - ctrl+alt+g or shift+alt+g <br /><br/ >
Email : <input type="text" name="type-email" id="type-email" /> <br />
Re-Type Email : <input type="text" name="re-type-email" id="re-type-email" /> <br />
</form>
</pre>
<script type="text/javascript" src="jwerty.js"></script>
<script type="text/javascript">

jwerty.key('ctrl+alt+g/shift+alt+g', function () {
    window.location = 'http://google.com.sg';
});

jwerty.key('ctrl+v',function (){
    alert('Suggest you not to use paste command while re-typing email');
    return false;
},'#re-type-email');

jwerty.fire('enter','input:first-child', "#myForm");

</script>

With this, i was expecting focus to be set to Email text field when enter key is pressed but its not happening... Please let me know whether i understand the fire event wrongly or is there a problem with it..

Thanks,
Abdul

How do I target numpad non-numeric buttons, like dot/delete?

Here is the code that I am working with:

$('input').on({
    keydown : function(e)
    {
        if ( jwerty.is('./num-./num-delete/num-dot', e) )
        {
            alert('dot');
            return false;
        }
    }
});

But, it appears to only trigger the alert on the default "dot".

How do I target the numpad one?

Disabling jwerty from focused textarea, input, select, etc

Hello!

Looking through your extended readme it looks like this should be possible but I'm having a hard time tracking down what I might be doing wrong

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
<script type='text/javascript' src='../lib/jwerty.js'></script>

<input id='q' name='q' />

<script>
    focus_input = function(){
      jQuery('#q').focus();
      return true;
    }

    alert_j = function(){
      alert('j');
      return true;
    }

    jwerty.key('i', focus_input);
    jwerty.key('j', alert_j);
    jwerty.key('j', false, '#q');
</script>

In this case I bind "i" to focus on that form input and "j" to alert the letter "j".

I expect that when the element is focused on #q, however, that the "j" key event will not fire as specified in the last line within the script tag.

Desired effect:

  • hit i key => focus on #q form input
  • hit j key => "j" shows up in input but no alert is triggered

Current (undesired) effect:

  • hit i key => focus on #q form input
  • hit j key => "j" shows up in input and alert is triggered

Looking forward to your thoughts!

Using the latest jwerty and jQuery 1.10.2

A way how to detect/scan pressed shortcuts

Let's say I want a users to be able to change their shortcuts, so I need a way how to detect what are they pressing. Something like:

var newShortcut = oldShortcut;
var scanner = jwerty.scan(function (shortcut) {
    // 'shortcut' in a format usabe by jwerty.key();
    console.log(shortcut); // ctrl+shift+g
    newShortcut = shortcut;

    // disables default action & bubbling
    // no need for that when changing shortcuts
    // previously bound shortcuts should also not fire
});

// When user is finished, he saves the shortcut
$('#save-shortcut-button').on('click', function () {
    shortcuts.change('some_action', newShortcut);
    scanner.stop();
});

That's just what my mind vomited in last 30 seconds, I hope you catch my drift :)

Can't create "combos" of single dead key

Jwerty is so cool, that you want to use it to manage about all your needed key events (in the context of a web app, say). But, one limitation is that you can't create a combo of a single deadkey (ctrl, alt, shift, meta). Would be good if it was possible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.