It all comes down to separation of concerns. When programming, separation of concerns deals with creating clear and concise boundaries between application components that have different responsibilities but work together to carry out a common overarching goal. So it is with the development of web user interfaces using HTML5, CSS3, and JavaScript. Each of these technologies work together to create interactive and beautiful user interfaces within the browser, but they each have very specific jobs that make these interfaces possible.
HTML: structures content in a very semantic (meaningful) and ordered way.
CSS: beautifies HTML by adding visual enhancements such as color, gradients, borders, padding, margin, fonts, animations, and positioning.
JavaScript: adds behavior to HTML, allowing HTML to respond to DOM events as users interact with the web page within the browser.
Together these three technologies create a very powerful tool set for the modern web developer and web user interface designer. The difficult part for most web developers is not allowing the three, very closely related technologies, to bleed across their boundaries into each other creating tightly coupled code. This tightly coupled code is usually a result of CSS and JavaScript being placed directly in the HTML.
Unobtrusive method to the rescue. Merriam-Webster defines the word unobtrusive as not attracting attention in a way that bothers or annoys. Well, mashed together HTML, CSS, and JavaScript is bothersome and extremely annoying, especially when it comes to maintainability and defect repair. For this reason developers have begun to make sure their web user interfaces are completely separated. This is accomplished by following a few specific rules:
HTML
- keeping HTML markup in separate files
CSS
- keeping CSS markup in separate files
- referencing those files in the ‘head’ element of the HTML files
- never use ‘style’ elements in HTML
- never use ‘style’ attributes on HTML elements
JavaScript
- keeping JavaScript markup in separate files
- referencing those files in the ‘head’ element or at the bottom of the ‘body’ element of the HTML files
- never use ‘script’ elements to hold JavaScript code in HTML
- only use ‘script’ elements to references a JavaScript file
- never use HTML element attributes that bind to DOM events such as ‘onclick’ or ‘onmouseenter’
Unobtrusive JS Example:
<!--DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>JavaScript Event Binding</title>
<script src="jsEventBinding.js"></script>
</head>
<body>
<div id="click-me">Click Me</div>
</body>
</html>
/**
* Created by Tim on 9/9/14.
*/
'use strict';
var elem = document.getElementById('click-me'); // a DOM element
elem.onclick = function () {
// Do something nifty here
};
Published by