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?

0

2 Answers 2

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'); } 
Sign up to request clarification or add additional context in comments.

1 Comment

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 #
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>

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.