Browser behavior on keypress
I ran into a good reminder today. A feature I was working on has a search form, which should make an external ajax call when typed in or enter is hit. It looked something like this:
<form class="search-form">
<input type="text"data-action="performSearch" />
</form>
events: { 'keyup': 'performSearch' }, performSearch: function(e) { if (e.keyCode === 13) { e.preventDefault(); } ... }
The default behavior upon hitting enter within a form is usually to submit that form, hence we use javascript's event.preventDefault, which is pretty standard.
However, every time I was hitting ‘Enter’, the form would be submitted and the page would refresh. At the same time, I was still hitting the performSearch if clause, but only after the submit had already been triggered.
The solution is fairly simple, just use keydown instead (you could listen to the keypress event as well if you wanted). What was happening is that Chrome submits the form on keydown rather than keyup. It was a great reminder that a lot of the behaviors are determined by the client side browser, so there's always a possibility of quirkiness!