4

I want to be able to have a trigger on keypress for %. So far, I have this:

$(iframeDocument).find('body').on('keydown', function(event) {
    if (event.which == 53) {
        alert("% pressed");
    }
});

But, it will also trigger when I press "5". How can I differentiate between the two?

Tushar
  • 85,780
  • 21
  • 159
  • 179
coffeeak
  • 2,980
  • 7
  • 44
  • 87

2 Answers2

6

You can use shiftKey property in the event object to check if the SHIFT is pressed when the event occurred.

var keyCode = event.which || event.keyCode;

if (event.shiftKey && keyCode === 53) {
    // Shift key is pressed
    console.log('% pressed');
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • Some keyboards could have a different character on the 5 key. On a german keyboard if the user presses shift and 3 they are not trying to make a # – Curtis Aug 01 '18 at 03:30
2

Use event.key. It's visible on the demo in the jQuery documentation for .keydown().

$(iframeDocument).find('body').on('keydown', function(event) {
    if (event.key === '%') {
      console.log(event.key + ' pressed');
    }
});

MDN describes this property:

If the pressed key has a printed representation, the returned value is a non-empty Unicode character string containing the printable representation of the key.

Just so you're aware, this property is not completely cross-browser compatible. See caniuse for a comprehensive list of supported and unsupported browsers.

If you're curious to mess around and see what values it yields, try this demo (it uses React just for fun):

class Label extends React.Component {
  static keydownListener(event) {
    this.setState({ label: event.key });
  }

  constructor() {
    super();

    this.state = { label: 'Press any key' };
    this.listener = Label.keydownListener.bind(this);
    
    window.addEventListener('keydown', this.listener);
  }
  
  componentWillUnmount() {
    window.removeEventListener('keydown', this.listener);
  }

  render() {
    return (
      <div>{this.state.label}</div>
    );
  }
}

ReactDOM.render(<Label />, document.body);

window.focus();
html, body {
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
  • `event.which`, surely? There's also an `event.keyCode` which appears to be an equivalent. But I don't find an `event.key` when debugging a `keyDown` event handler. – BobRodes Jul 22 '16 at 04:53