Please login or register.

Login with username, password and session length
Advanced search  

News:

You need/want an older version of sNews ? Download an older/unsupported version here.

Author Topic: Removing inline Javascript  (Read 7414 times)

centered

  • Guest
Removing inline Javascript
« on: September 29, 2008, 12:31:02 AM »

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: [Select]
<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>

Now let's remove the inline onClick event

Code: [Select]
<!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>
« Last Edit: September 29, 2008, 12:32:48 AM by equilni »
Logged