Example one

Javascript is a different layer of the style and structure ones, and like CSS, it should not be required but optional, so that without its use the page should be accessible and usable. If the browser cannot interpret the code it will not execute it, but the contents will be accessible. This is generally called script degradation. Now, being more specific, what makes a piece of code unobtrusive?

  1. Mix with structure: mainly, script behaviour not being mixed with page contents. This means there will be no intrinsec events inside the document and the file will be stored in a separate .js file.
  2. Initialization: the ideal solution is the script being initialized automatically on page load
  3. Assign actions with an event handler: because we have avoided the use of intrinsec events we will need a way to associate actions (execute functions) to events captured by different elements on the page.
  4. Compatibility: browsers that dont understand the code must do without it throwing no error messages.
  5. Capacities detection: to allow the previous point be true we will use object detection instead of browser detection.

Ending example one.

As you'll see next, I also modified it so the page could handle more than one scroller, even with different sizes, as that was another requirement for that website. So I created a function that added a counter to an array and we pass as arguments the index of that instance and the size for that scroller. The script just does the rest.

Example two

Table of Contents from titles (TOC)

This script reads all nodes in a document and stores the titles hierarchic structure in a variable, showing them in an indented list according to their order. Sections of the list are links to the real section on the page, using the id of the titles (script creates them if needed).

Download toc
Form validator

This script reads all text fields of a form making all "required" classes having to be filled before sent to server, otherwise warning visually and through an alert. If the field is named email it forces (with a regular expression) to use a valid email.

Download validador

Ending example two.

I think it's quite easy to implement, you need:

Once you accomplish these the script will do the rest for you. You can download the script with all the needed files in raw format from here