When the user sets the focus to an edit control on my HTML page, I want some other text to appear “around” it, to give some hints for how to fill out the edit control, and some buttons to fill it with random data. What’s the best way to do this with javascript or jquery or whatever?
Thanks.
You can hook the
focusandblurevents of the control, and use them to show and hide the elements you want to show and hide.Example 1 – Unobtrusive
You can do this without putting Javascript in your markup by using IDs and DOM methods. For instance, given this markup:
You can hook the events using your favorite Javascript library (jQuery, Prototype, Closure, etc., etc.). Or here’s a lame example not using any of them:
I wouldn’t literally do it that way (I’d generalize things, use a library to make it easy to look things up by attribute, use an attribute to relate things rather than IDs and a naming convention, etc., etc.), but you get the idea.
Example 2 – Unobtrusive and general, using Prototype
Just by way of example, here’s an approach using Prototype which is much more generic. A field and its help are related by the field name and the help element’s
data-help-forattribute.HTML:
Javascript:
Example 3 – Intermixed and fragile
Just to show a range of options, you can also intermix your Javascript and HTML, and use relative methods (which are more fragile — if you change your display slightly, you can break things pretty easily). But:
HTML:
Script:
But again, the above is very fragile to the structure — put in another
spanfor whatever reason between the field and its help, and the wrong one gets shown/hidden.