views:

53

answers:

2

Hello,

I want to simulate a couple of clicks. A 'Save' and 'Cancel' anchor clicks.

I have this as my enter simulation

$('.group').live('keypress', function(e){
    code = e.keyCode ? e.keyCode : e.which;
    if(code.toString() == 13){
        $(this).find('a.saveChanges').click();
    }

});

and this as my esc simulation

$('.group').live('keypress', function(e){
    code = e.keyCode ? e.keyCode : e.which;
    if(code.toString() == 0){
        $(this).find('a.discardChanges').click(function(){
            GROUP.find('.group-text')
                .text(GROUP.data('origText'))
                .end().removeData('origText');
            GROUP.find('.groupcount').fadeIn('slow');
            GROUP.find('.group-image').fadeIn('slow');
            GROUP.removeClass('editmode');
        });
    }
});

My enter seems to work perfect, but my esc doesn't. I'm running this in Firefox at the moment.

+3  A: 

Just use e.which. jQuery normalizes it for you across browsers.

Then test for 27.

EDIT: It also looks like you need to use keyup instead of keypress for some reason with the ESC key.

Example: http://jsfiddle.net/uRE7x/

$('.group').live('keyup', function(e){
    if(e.which == '27'){
        $(this).find('a.discardChanges').click(function(){
            GROUP.find('.group-text')
                .text(GROUP.data('origText'))
                .end().removeData('origText');
            GROUP.find('.groupcount').fadeIn('slow');
            GROUP.find('.group-image').fadeIn('slow');
            GROUP.removeClass('editmode');
        });
    }
});
patrick dw
oh cool, ya i did exactly that when i read your comment but it wasn't working so i thought i was getting what you had said wrong. but yes your right they keyup is what was messing up with me ;-)
s2xi
More type coercion? Try just `e.which === 27` instead.
Ben Blank
ya, i noticed that and fixed it on my side when I compared what I had to what he had proved ;)
s2xi
@Ben - Interesting, [the docs state](http://api.jquery.com/event.which/) that `event.which` returns a String. Not the case. Anyway, `===` is better, but if the docs were accurate, `e.which === 27` would fail.
patrick dw
@patrick — I think that's part of the key event confusion. Some of the key event properties are strings when the key pressed is a printable character (e.g. `"a"` instead of `65`), but jQuery's normalization *should* ensure that `key.which` is always a number. Even if it weren't, I believe it would be `"\x1b"` (DEC 27), not `"27"`.
Ben Blank
Have I mentioned key events give me a headache? ;-)
Ben Blank
A: 

Since you didn't provide any html, I just focused on esc functionality. esc is character 27, probably why your function isn't working.

  <html>
    <input></input>
    <script>
    $(document).delegate('input','keypress', function(e){
        code = e.keyCode ? e.keyCode : e.which;
        if(code=== 27){
            alert('esc pressed');
        }
    });
    </script>
  </html>
Drew