Javascript recipes

From ShawnReevesWiki
Revision as of 09:30, 3 April 2013 by Shawn (talk | contribs) (Created page with "==Javascript recipes== This is a repository for snippets and methods that help web pages interact with viewers. ===Let a user know a form-element has changed=== Sometimes we'...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigationJump to search

Javascript recipes

This is a repository for snippets and methods that help web pages interact with viewers.

Let a user know a form-element has changed

Sometimes we're looking at a form and don't know whether we've changed anything. Javascript allows different methods, including a couple shortcuts that get the job done, if not perfectly. You can add an attribute to any form-input that makes either a key-press or a change in content activate a function. I like to hide a "submit" button until the content of a form has changed—A reminder that there's something to submit.

onchange
This attribute will activate a command, given as the value of the attribute, when the content of the input changes. One problem is the action only happens after the focus has left the input field, so one can type into an input and still not see the expected event.
onkeypress
This attribute will activate as soon as any key is pressed while the input is in focus. This solves the problem mentioned with onchange. The only snag is that it is possible to change a field without the keyboard, for example with the mouse and menu commands.
onfocus
This attribute will activate as soon as the field comes into focus. This would be jumping the gun, because one might select a field without making any changes.
onpaste, oncut
These attributes can complement onkeypress to account for mouse actions that might change text.