Basic Javascript (DHTML) TutorialJavascript is a scripting language whose source code is downloaded along with the HTML code of your page, and is executed by the browser once the page has loaded. Javascript has syntax similar to that of Java (or C), but is easier to program. Javascript is wired up so that it has full programmatic access to all of the HTML tags within your page. You can read, write, change and delete tags using Javascript functions to produce an almost limitless scope of interesting effects. This JavaScript tutorial is indended to give the reader a quick introduction to the basics of Javascript which then lead us on to producing more interesting Javascript applications, such as menus and form validation - two of the most common uses of Javascript. Where do JavaScripts go?
Like CSS, Javascript may be included inline to your HTML page using a special container tag, in this case the
The script tag should to be told which language to use using the
You may also include an external JavaScript file by adding a Example 1 - Hello WorldHere's a first classic "Hello, World" example which displays a message box when the page loads.
In this example we use the alert() function to display a message box. The alert function takes a text string as an argument for what to display in the message box. The following are some code snippets that build on the first basic example, showing you more JavaScript language features and techniques. Example 2 - Using
|
|
<script type="text/javascript"> var colour = prompt("What is your favourite colour?", ""); if (colour != "") { alert("Your favourite colour is " + colour); } </script> |
| View Source Run Example |
The prompt function displays an input box which returns a variable containing the user's value. If the user clicks cancel or doesn't enter the variable, a
empty text string is returned. We use an if statement to see if the variable contains any data, and if it does, we notify the user
of their choice once again using the alert() function.
varvar tag = document.getElementById(?box?); var string = ?Hello, World?; var number = 123;
Our examples have been quite dry so far - let's use JavaScript to start changing some properties on the page. In this example we'll extend the previous example to changes the page's background to the user's favourite colour.
|
<script type="text/javascript"> var colour = prompt("What is your favourite colour?"); if (colour != "") { document.body.style.backgroundColor = colour; } </script> |
| View Source Run Example |
The code is pretty straighforward. We can get an object reference to the body tag (whose background property we'll change) using document.body.
Once we've got the body tag, we can simply change a member of its style object, in this case the backgroundColor property.
You'll notice that for almost every property we can specify in CSS or via HTML attributes, there is an equivalent object property in JavaScript. The Document
Object Model (DOM) is a standardised model which defines how we can access all of these attributes from JavaScript functions.
For example, the CSS Class attribute (class="cssClass") of a tag is equivalent to the object.className property. We'll have a go at changing the class of an object
in a later example.
Each time we've created a JavaScript that executes immediately, and only once. What happens if we want to run our code at a different time - or more than once. This time we'll update our previous example to use JavaScript functions
<script type="text/javascript"> function chooseColour() { var colour = prompt("What is your favourite colour?"); if (colour != "") { document.body.style.backgroundColor = colour; } } </script> <a href="javascript: chooseColour();">Choose Colour</a> |
| View Source Run Example |
This time we've enclosed our JavaScript within a function { }. Like any sub routine in a programming language, this function won't now run until it's called.
We prefix the href with "javascript: " and the name of the function. Now that we've used a function, we can call it over and over again.
This time we'll move on and change the CSS class instead. We'll also change the property of something other than the body tag, which is slightly more difficult.
<style> .class1 { background-color: red; color: white; width: 100px; height: 100px; border: 1px solid black; text-align: center; } .class2 { background-color: white; color: red; width: 100px; height: 100px; border: 1px solid black; text-align: center; } </style> <div class="class1" id="box" onClick="toggle();"> Click Me! </div> <script language="JavaScript"> function toggle() { var obj = document.getElementById("box"); if (obj.className == "class1") { obj.className = "class2"; } else { obj.className = "class1"; } } </script> |
| View Source Run Example |
We start off by defining two distinct CSS classes. The first has a red background and the second a white background.
Secondly we define a div tag define the onClick attribute which allows us to call a function every time
the box is clicked on, and set a unique identifier in the tag's id attribute.
The JavaScript function first gets a reference to the tag using the document.getElementById() function which (unsurprisingly) gets a reference to the object
with a particular id. The function then checks the tag's className attribute, and swaps it over.
this statement
We've seen how JavaScript functions allow us to reuse code. The code above, however, only works for one box as the function itself has the name of the
object to change "hardwired" into it. What would be better is to pass the object to change to the function, which can then do the work for many different
objects.
This time we'll try a different event caller - the onMouseOver and onMouseOut attributes.
<style> .class1 { background-color: red; color: white; width: 100px; height: 100px; border: 1px solid black; text-align: center; } .class2 { background-color: white; color: red; width: 100px; height: 100px; border: 1px solid black; text-align: center; } <div class="class1" onMouseOver="over(this);" onMouseOut="out(this);"> Box 1 </div> <div class="class1" onMouseOver="over(this);" onMouseOut="out(this);"> Box 2 </div> </style> <script language="JavaScript"> function over(obj) { obj.className = "class2"; } function out(obj) { obj.className = "class1"; } </script> |
| View Source Run Example |
This time we're using two functions - one to highlight the box and one to de-highlight the box.
We don't need to use the document.getElementById() function this time - we get the object passed to the function directly. To do so, we use the this keyword, which allows the tag to send a reference
to itself as an argument to the function.
We'll take a break from the className property for now, and play with a different property - the innerHTML property.
The innerHTML property allows us to manipulate the code within a tag.
For example:
The innerHTML of the following <body> tag:
<body><h1>My Page</h1></body>
Would be: "<h1>My Page</h1>"
<script language="JavaScript"> var quotes = new Array(); quotes[0] = "'Only two things are infinite...'. |
| View Source Run Example |
Here our JavaScript code defines an array. C/Java programmers: don't worry about the size of the array - Javascript expands the array size automatically.
We define our array and currentQuote variables outside of the function allowing them to act as global variables. The getQuote
function cycles the innerHTML property of the box tag through the different values stored in the array.
You'll notice that the innerHTML may contain further HTML inside it.
document.write() function. In the next tutorial we'll use is extensively to create JavaScript menus.