Java Reference
In-Depth Information
Unobtrusive JavaScript
When JavaScript was initially used, it was designed to be inserted directly into the HTML
code as can be seen in this example:
<a id="button" href="#" onclick="alert('Hello
World')">Click Me</a>
This made it difficult to see what was happening as the JavaScript code was mixed up with
the HTML. It also meant that the code was tightly coupled to the HTML, so any changes in
the HTML required that the JavaScript code would also need changing to stop it breaking.
It's possible to keep the JavaScript code on its own away from the HTML by placing it inside
its own <script> tags, like so:
<script>
button = document.getElementById('button')
button.addEventListener("click", function() {
console.log("Hello World!");
};
</script>
Unobtrusive JavaScript is when the JavaScript code is kept completely separate from the
HTML and CSS, preferably in its own file. This can be linked to using the same script
tag and the src attribute to specify the file to link to:
<script src="js/scripts.js"></script>
The JavaScript code would then be placed in a file called scripts.js.
Warning: Avoid Using Self-closing Tags
If you've used XML or XHTML, you might have come across self-closing
tags such as this script tag:
<script src="js/scripts.js" />
 
Search WWH ::




Custom Search