Introduction to JavaScript
Posted in JavaScript | Posted on 27-03-2010-05-2008
Okay, so you have learned the basics of HTML. But you have discovered HTML’s limitations. You want some interactivity and cool effects on your site. Believe it or not, that interactivity and those effects can be achieved with JavaScript.
Unlike server-side scripting languages such as PHP and ASP, JavaScript is a client-side scripting language. What this means is that you do not need to have access to a web server to practice writing your JavaScripts. You can run your scripts right from your web browser.
Let’s take a look at two ways we can insert JavaScript into our HTML page.
In this example, we are inserting an external JavaScript. You can insert this line of code within the head tags. What we have here is an HTML tag declaring a script. Our script type is JavaScript. The source is a file with the JavaScript code. Hypothetically what is happening here is we are calling codes of JavaScript that are stored in a file called myfile.js. Note how we close the script. If you don’t close the tag; like any other unclosed HTML tag, you might get unexpected results. Again this is just an example of how you can insert JavaScript into your web page.
Now we will insert JavaScript directly into a web page. Let’s work off this example:
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=”content-type” content=”text/html; charset=iso-8859-1″ />
<title>JavaScript Introduction</title>
<script type=”text/javascript”>
alert(‘Hello World’);
</script>
</head>
<body>
<script type=”text/javascript”>
document.write(‘<h1>JavaScript is Cool!</h1>’);
</script>
</body>
</html>
Run this script on your browser. Before the page loads, you should see an alert box. Click the ok button. Then a message should be displayed on the screen.
Here’s how we did it.
This is how we got the alert box to pop up before the page loaded.
If you look at the entire HTML code, you will notice that this line of code is within the body tags. Here we simply used document.write to write the lines in the parenthesis. Take note of the syntax we use; particularly the quotation marks.
This is just basic stuff. Large amounts of JavaScript code can become confusing and complex to read. That is why it is very important to first understand the basics.
