Obtrusive JavaScript has no non-JavaScript alternative and therefore renders a feature inaccessible to users with JavaScript disabled or unavailable in their browsers. Such users include the visually impaired (who use special browsers) and employees of corporations which strip JavaScript from pages and/or disable it in the browser for security reasons.

The first step to unobtrusive JavaScript is to build the page without client-side scripting, and make sure it works. Any server-side logic that JavaScript will need to use should be kept in separate script files than the alternative pages.

Next, you need to make some JavaScript run after the page is loaded which modifies the page with event-listeners. This involves finding the elements to modify (usually with document.getElementById) and assigning to their "on[...]" properties, for example "onclick".

After you complete the first step, all your links should look like this:

<a href="foo.php?bar=baz">FOO!</a>

We need an ID to find it with, so...

<a id="fez" href="foo.php?bar=baz">FOO!</a>

Now we can JS-enable that link when the page loads:

document.getElementById('fez').onclick = function (){
    return false;

Waiting for the pageEdit

There are two ways to wait for the page to load, favored by different people for different reasons.

You can register an onload event-listener on the window. This is equivalent to <body onload> except that logic and layout aren't jumbled together.

window.onload = function (){

Scripts placed in the body are run when the browser reaches them. For example, this script will be run after the form is loaded but before the footer exists:

        <script lang="text/javascript">
        <div id="footer"></div>

Some people (most notably Douglas Crockford) prefer to put scripts at the very bottom of the page.

"A <script src="url"></script> will block the downloading of other page components until the script has been fetched, compiled, and executed. It is better to call for the script as late as possible, so that the loading of images and other components will not be delayed. This can improve the perceived and actual page loading time. So it is usually best to make all <script src="url"></script> the last features before the </body>. An in-page <script> does not have a significant impact on loading time.
"If a script is defining functions or data that are used by other functions, then the defining must be done before use. So the defining scripts must come before the using scripts." [1]

Ad blocker interference detected!

Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.