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/third-party/jquery.js"></script>
<script type="text/javascript" src="http://www.epa.gov/epafiles/js/epa-core.js"></script>
The first file is jQuery, a JavaScript framework that
... "simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is designed to change the way that you write JavaScript."
The second script is a set of core EPA functions, described below.
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.
Core EPA Functions
EPA has a core JavaScript file that runs multiple functions on page load, including:
- Inserting the "Page last updated" date and the page URL into the footer
- Providing a simpler way of creating a "New!" icon, using the
<ins>(insert) element - Targeting site-wide announcements to specific pages:
- EPA, AA/RA and Program Office home pages
- All pages
- Providing alternate colors for data tables rows.
- Suggesting search terms when you use the search box
- Rendering the Share links in the upper right of every page (What is this?)
- Any jQuery plugins you're using
