Let’s say you’re viewing different pages in your browser, and in the midst of your browsing you decide to visit Google’s home page. So you see this:
If you happen to change your mind about typing a search, and you want to go “back”, you can do one of two things. You can (1) use the back button in the browser, or (2) you can use the backspace key on your keyboard (on a Mac it’s the “delete” key).
If you decide to use the keyboard method, your experience will be broken, because when you’re inside a text field, the “backspace” key means “delete text”. So the browser will not go back in its history, as you would expect. And naturally, shift-backspace (which is forward in history) would likewise fail.
The script does the following:
- Look for keystrokes in the text field
- Make sure the field is empty after the keystroke
- Check if the key pressed is the backspace (8) or delete key (46)
- If it is, check if the shift key is being pushed
- Go back or forward in the browser history
The script seems to work in every browser except IE8. And oddly, although I’ve added the ability to use shift-backspace (shift-delete on Mac) to go forward in browser history, IE10 doesn’t seem to recognize this shortcut like previous versions of IE seemed to do (if I remember correctly).
Besides the IE flaws just mentioned, one of the flaws in this script is the fact that the keystroke that it looks for can be either backspace or delete (which ensures it works on PC and Mac). So the result of this is that if you push “delete” on a PC keyboard (which is a different button than “backspace”), it too will cause the history-back functionality to occur. But I don’t think that’s such a big deal, really.
Finally, the other flaw in this is that if someone deletes what they were typing in the search box and they hit backspace/delete one too many times, it will cause the history-back fuctionality to trigger. I started to try to figure out how to cancel the event once the user begins to type actual visible text, but couldn’t figure out how to do it. Maybe someone can fork the CodePen and add that to it.
The demo seems to work fine on CodePen, but because because CodePen embeds the full-page view in an iframe, it seems a little unnatural, so I’ve provided a bare-bones demo to test instead, using the button below.
And obviously, if you click the demo button below, stay in the same tab, so you’ll have something to go “back” to.