introduction to javascript

what is it?

  • a programming language similar to Java, but simpler to use;

  • an interpreted language - no machine compilation involved;

  • it's client-side scripting executed in the machine of the user - the instructions are interpreted by the browser and do not need to call the server;

  • it can relieve the server of some tasks: show local calculations, identify the browser being used and modify the display accordingly, etc.;

  • it is case-sensitive, so be careful with the use of upper or lower case for function names, variables, etc.

how is it run?

The script can be included in the <head> section, in the <body> or in an external file.

The script is identified by the following tags:
<script type="text/javascript"> .... </script>

In <head>:

In <body>:

The external file containing the script is identified by src="file.js":

If you look at the menu line at the top of this page you'll see today's date displayed. The date is taken from your computer and formatted with javascript. Here is an example of two ways to do that:

This works:

But this is much better:

The advantage of doing it with a file is that the file can be called at any point in any page and it avoids a lot of copy/paste.

Here is the code for the javadate.js file. You can create your own file and copy/paste this code into it. Be sure to save it with the extension .js

var mydate=new Date() 
var year=mydate.getFullYear() 
var day=mydate.getDay()
var month=mydate.getMonth() 
var daym=mydate.getDate() 
if (daym<10) 
var dayarray=new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday") 
var montharray=new Array("January","February","March","April","May","June","July","August","September","October","November","December") 
document.write(dayarray[day]+", "+" "+montharray[month]+" "+daym+", "+year)

script with events

A script is not always called automatically like javadate was.

When you write the script in <head> it is activated when the page opens. Then it can be called by an event that occurs in the page, for example a mouseover.

In these two examples a message appears when you run the mouse over the link text. You can then do <Esc> and <Click> to execute the action, or close the message window.

Next page

Back to Content

This is the xhtml code for the OnMouseOver event:

Note that the event calls the function described in the javascript in the <head> section.

In the next lesson we'll start to look at the syntax and structure of javascript that will allow you to run the scripts that you need. .


Previous            Next