May 23rd, 2009
This one could save you lot of time In short, the answer is to “return false;”. That’s it. If you want to know more details, read ahead.
Say, you have an awesome page where you want to disable right click and also disable Ctrl+C (copy), Ctrl+S (save page). The process is simple. Just register an event for right click and when the event fires, just return false. Since false is being returned, the browser will cancel the event.
Same goes with keyboard. ‘onkeypress’ event is fired whenever a key is pressed. To reject any key, just capture that event and return false. If you want to do anything special, just do it before returning false. Ctrl+S is interesting. In most web browsers (notably google chrome), it brings up the default Save Dialog. Most web apps have keyboard shortcuts these days & oh! 99% of them don’t return false, only to find the user experience irritating when the save dialog pops up; when something else should occur. Hence, if you wish to customize the functionality of the default browser specific keyboard shortcuts, do the following:
- Create an event handler and capture the event.
- Do something.
- “return false;”
That’s all. Have fun!