Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Voices That Matter

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

C: Separation of behavior and structure

Separation of behavior and structure is easy to understand: just don’t put any JavaScript code in your HTML page. This takes two steps:

  1. Put all JavaScript functions in a separate .js file that’s linked to from all HTML pages that need it.
  2. Remove all event handlers from the HTML and put them in the same .js file.

Functions in separate file

JavaScript code belongs in the .js file, and not in HTML files.

Therefore, this is wrong:

<script type=”text/javascript”>
function doAllKindsOfNiftyThings()
{
	// JavaScript code
}
</script>
</head>
<body>
<h1>My HTML page</h1>
[etc.]

But this is right:

<script type=”text/javascript” src=”nifty.js”></script>
</head>
<body>
<h1>My HTML page</h1>
[etc.]

// in nifty.js
function doAllKindsOfNiftyThings()
{
	// JavaScript code
}

We’ll discuss the technical aspects of <script> tags in 4D.

Remove event handlers from HTML

The second step in separating behavior and structure is to move all JavaScript calls within your HTML to the separate .js file. In fact, 99% of the JavaScript code in HTML pages consists of inline event handlers.

Here, the handlers are in the HTML, where they don’t belong:

<a href=”home.html”
	onMouseOver=”mOv(‘home’)”
	onMouseOut=”mOut(‘home’)”>Home</a>

Instead, define them in the separate .js file:

<a href=”home.html”>Home</a>

// in separate .js file
var nav = document.getElementById(‘navigation’);
var navLinks = nav.getElementsByTagName(‘a’);
for (var i=0;i<navLinks.length;i++)
{
	navLinks[i].onmouseover = [code];
	navLinks[i].onmouseout = [code];
}

The script takes the element with id=”navigation” (a <ul>, for instance) and accesses all of its links, then assigns onmouseover and onmouseout event handlers to them one by one.

The javascript: pseudo-protocol

Occasionally you’ll see javascript: pseudo-protocol links like the following one:

<a href=”javascript:doAllKindsOfNiftyThings()”>Do Nifty!</a>

This complicated and dirty code is secretly meant as an onclick event handler: when the user clicks on this link, we want to execute doAllKindsOfNiftyThings(). Therefore you should remove the javascript: call from the link and replace it with an onclick event handler in the separate .js file:

<a href=”somepage.html” id=”nifty”>Do Nifty!</a>

// in separate .js file
document.getElementById(‘nifty’).onclick = doAllKindsOfNiftyThings;

As to the href, it should contain either a URL that noscript users can follow, or the entire link should be generated in JavaScript. We’ll get back to this in 2F.

  • + Share This
  • 🔖 Save To Your Account