sNews 1.6 (previous version) > Suggestions

Removing inline Javascript

(1/1)

centered:
As the title states, to keep with the sperating structure/style/behaviour model of HTML/CSS/Javascript, we should remove the inline javascript. Why should we do this? To keep the html document clean, same reasoning we don't use inline CSS.

http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
http://alistapart.com/articles/behavioralseparation

To test, let's look at w3c school's innerHTML example
http://www.w3schools.com/htmldom/prop_anchor_innerhtml.asp


--- Code: ---<html>
<head>
<script type="text/javascript">
function changeLink()
{
document.getElementById('myAnchor').innerHTML="W3Schools";
document.getElementById('myAnchor').href="http://www.w3schools.com";
document.getElementById('myAnchor').target="_blank";
}
</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Microsoft</a>
<input type="button" onclick="changeLink()" value="Change link">
</body>

</html>
--- End code ---

Now let's remove the inline onClick event


--- Code: ---<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<head>
<script type="text/javascript">

window.onload=function() {
document.getElementById("changeClick").onclick=changeLink;
};

function changeLink() {
document.getElementById('myAnchor').innerHTML="Visit W3Schools";
document.getElementById('myAnchor').href="http://www.w3schools.com";
document.getElementById('myAnchor').target="_blank";
}

</script>
</head>

<body>
<a id="myAnchor" href="http://www.microsoft.com">Visit Microsoft</a>
<input id="changeClick" type="button" value="Change link">
<p>In this example we change the text and the URL of a hyperlink. We also change the target attribute.
The target attribute is by default set to "_self", which means that the link will open in the same window.
By setting the target attribute to "_blank", the link will open in a new window.</p>
</body>

</html>
--- End code ---

Navigation

[0] Message Index

Go to full version