Monday, August 22, 2011

JavaScript by w3schools

I was planning to slot in an entry on XML here, but I note the W3Schools tutorial on XML puts JavaScript as required knowledge. As I branched into web language revision because HTML and XHTML were required knowledge for JavaScript, I might as well start on that now.

I have to say that having praised the W3Schools tutorial on PHP, I am a little disappointed by this one. It is all over the place. I came here because the Mozilla Getting Started with JavaScript page began with a "corny" example but zero explanation of the language structure or syntax. And now this one does the same thing:

<html>
<head>
<script type="text/javascript">
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>

<h1>My First Web Page</h1>
<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>

It's rubbish without a proper explanation. If all I want to do is reverse engineer someone else's code, I won't bother with a tutorial, I'll just search for code examples.

So what do we have in the next few pages that is useful?

To insert a JavaScript into an HTML page, use the <script> tag. Inside the <script> tag use the type attribute to define the scripting language.

This is shown in line 3 of the code quoted above.

The lines between the <script> and </script> contain the JavaScript and are executed by the browser. JavaScripts can be put in the <body> and in the <head> sections of an HTML page. JavaScripts in an HTML page will be executed when the page loads. This is not always what we want. Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button. When this is the case we can put the script inside a function [which is called by the event].

This strategy is executed in line 4 of the code quoted above, where the function displayDate is defined, and in the third from last line, where a button click is set to call the function.

You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. It is a common practice to put all functions [either] in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content.

JavaScript can also be placed in external files. External JavaScript files often contain code to be used on several different web pages. External JavaScript files have the file extension .js. To use an external script, point to the .js file in the "src" attribute of the <script> tag:

For example:

<head>
<script type="text/javascript" src="xxx.js"></script>
</head>

I thought they might give an example of a .js document, but they did not.

Let's hope the XML lesson is more interesting.

No comments: