Writing JavaScript
Scripting Links of Note
A primary goal of the EPA Web Design is to stop mixing presentation with structure, making it easier to rebrand and change the look-and-feel throughout the site simply by changing the style sheet. Further separation is possible by avoiding inline styles and classes, and using inheritance and contextual selectors.
We're also applying the same thinking to JavaScript.
An advantage of JavaScript is that it comes in a separate file. Much like CSS, this means you can apply one collection of functions to every page of the site. If you need to change or add to its functionality, you can do that in one document rather than going through each page.
This means—unless there are special circumstances—all we ever need to see in EPA's Web template:
<script type="text/javascript" src="http://www.epa.gov/epafiles/js/epa-core.js"></script>
Note: There is a second line, calling the JavaScript file "extra.js". This JavaScript file currently contains the code for the American Customer Satisfaction Index (ACSI) survey. In the future, it can be repurposed for other functions the Agency may develop.
Unobtrusive JavaScript
Good, unobtrusive JavaScript has the following characteristics:
- web pages aren't dependent on it to work: it is an enhancement
- functions first check to see if an object is available. If not, then it fails silently.
- the HTML code isn't riddled with inline event handlers and JavaScript
- if someone has JavaScript off, nothing happens:
<noscript>
is unneccessary - does not rely on browser specific extensions
Unobtrustive JavaScript is used to apply events to desired elements from an external JavaScript file, usually when the page has loaded. For instance, to apply a certain event to some links (a
elements), loop through all of the links in the page and apply the events accordingly, e.g. if the element has a specific class name.
EPA Web Design has one JavaScript file that runs multiple functions on page load, including:
- Inserts the "Page last updated" date and the page URL into the footer
- Provides a simpler way of creating a "New!" icon, using the
<ins>
(insert) element - Targets site-wide announcements to specific pages:
- EPA and AA/RA home pages
- EPA, AA/RA, and Program Office home pages
- All pages
- Provides alternate colors for data tables rows.