Javascript: the Beginning - Adding Javascript to an HTML Page
(Page 2 of 4 )
Traditional programming tutorials want you to write a program that prints the phrase, "Hello World!" to the screen. It's similar to learning your first song on guitar or bass. They always teach you Smoke on the Water. Always.
Well not today my friend. Today we break away from tradition.
<html>
<body>
<script type="text/javascript">
document.write("I'm here to kick butt and chew bubble gum. And I am all out of bubble gum...")
</script>
</body>
</html>
The above code will print the following:
I'm here to kick butt and chew bubble gum. And I am all out of bubble gum...
The tag <script type="text/javascript"> tells the browser that the following code is JavaScript. If you were to leave this code out, this is what would have printed:
document.write("I'm here to kick butt and chew bubble gum. And I am all out of bubble gum...")
The portion of the code that begins document.write is the command used to print text to the monitor.
Formatting Text
Just as we can embed JavaScript into our HTML, we can place HTML inside of our JavaScript. Here is an example:
<html>
<body>
<script type="text/javascript">
document.write("I don't like gum. I <i>love</i> it.")
</script>
</body>
</html>
This results in the following being printed to your screen:
I don't like gum. I love it.
Any Comments? Keep 'em to Yourself
Unless they are good comments that is. If you have those send them on in. Maybe I will get that raise from $5.50 an hour to $6.00 (*fingers crossed*) after all.
You use comments in JavaScript (and any other programming language) to leave notes to yourself or future programmers regarding your code. It's a lot easier when you have to go back and fix a mistake if you can see a comment and know right off the bat what you were intending to do with it.
You use two forward-slashes (//) to comment in JavaScript. When the browser sees these, it ignores any text following it on that line.
<html>
<body>
<script type="text/javascript">
document.write("<i>Hello</i>") //This is a comment.
// Here is another comment
</script>
</body>
</html>
The above code would simply print Hello to your monitor.
Next: Putting JavaScript in its Place >>
More JavaScript Articles
More By James Payne