Basic JavaScript
JavaScript is a very easy way to add all sorts of dynamic elements to your site. Unless you've had some programming experience, JavaScript will be quite a new concept at the start — it's fairly different to HTML. In this tutorial we'll be laying some groundwork on the language, and writing our first script.
This page was last updated on 2012-08-21
What is JavaScript?
JavaScript is a simple scripting language invented specifically for use in web browsers to make websites more dynamic. On its own, HTML is capable of outputting more-or-less static pages. Once you load them up your view doesn't change much until you click a link to go to a new page. Adding JavaScript to your code allows you to change how the document looks completely, from changing text, to changing colours, to changing the options available in a drop-down list (and much, much more!).
JavaScript is a client-side language, which means all the action occurs on the client's (reader's) side of things. This means that no trips to the server are required for JavaScripts to kick into operation, which would slow down the process enormously. JavaScript operations are usually performed instantaneously. In fact, JavaScript is often used to perform operations that would otherwise encumber the server, like form input validation. This distribution of work to the relatively quick client-side service speeds up the process.
JavaScripts are integrated into the browsing environment, which means they can get information about the browser and HTML page, and modify this information, thus changing how things are presented on your screen. This access to information gives JavaScript great power to modify the browsing experience. They can also react to events, such as when the user clicks their mouse, or points to a certain page element. This is also a very powerful ability.
Most importantly, JavaScript isn't overly tough to learn and use. It's a little technical, yes; but after just a few tutorials you'll have some useful scripts in your pages, and will have the knowledge necessary to modify and use the countless free scripts available across the web.
Browser Compatibility Note:
JavaScript is supported by Netscape 2+, Internet Explorer 3+, Opera 3+ and most of the other modern web browsers. Each new version of the main browsers has supported new generations of JavaScript commands, each more complex than the last. Script compatibility can still be a problem, as the language is not as standardised as HTML; but this is being worked on.
The Java Connection
Understandably, JavaScript's connection with Java is regularly misunderstood. They are not the same thing.
- » Java, created by » Sun Microsystems, is a full computer programming language like C++, suitable for writing complete, large-scale programs.
- JavaScript, on the other hand, was created by » Netscape. It was based to some degree on Java — the syntax of the code is very similar — but it is very rarely used for anything outside of a browser. It was actually originally to be called 'Live Script', but Java's increasing popularity at the time made Netscape change the name for marketing reasons.
A scripting language can be thought of as a lightweight programming language; one that can be interpreted by a browser without needing to be compiled first. The script is actually just some commands that the browser has to do.
The two share many similarities. Most prominent of these is that they are both forms of Object-Oriented Programming, or OOP. This means that you work with small objects that are combined together to form larger objects. We'll get into that more in a minute.
You may have heard of Java being used alongside HTML through things called applets. These small-scale applications can be embedded into pages for very advanced effects, but they aren't entirely practical, due to large file sizes and limited extra utility. JavaScript on the other hand, can be very useful.
Versions
Like seemingly every tool we use to create our sites, JavaScript has been arriving in versions, ever since version 1.0 which turned up in Netscape Navigator 2. In subsequent versions JavaScript graduated through versions 1.1, 1.2 and 1.3. Microsoft made an attempt at JS 1.0 support in Internet Explorer 3, but it was bugged to bits and was very unreliable. Microsoft dubbed their version “JScript”. The latest generation of browsers have decent support for JavaScript 1.3.
Coders' dismay at the incompatibilities wrought by the two browsers' different levels of support eventually lead to a standardised version of JavaScript, sometimes called ECMAScript, after its standardisers, the » ECMA. Modern browsers like IE8, Firefox and Safari have good support for this standard, and a lot of work has gone on recently to ensure that all browsers are operating on the same DOM...
The DOM
The DOM, or Document Object Model, is the framework that JavaScript works off. Remember how I said JavaScript is a form of Object-oriented programming? This concept means we can think of all the elements that go into making a page as objects. The document itself is an object, made up of other objects like forms, images and tables. Form objects are also made up of even more objects like text boxes and submit buttons.
All of these objects have properties, with values that define their colour, their length etc. JavaScript can read these properties and modify them, or react to events that happen to the objects, instantly changing the object in the browser window. A script can respond to user interaction with the page or can run all by itself.
Actions that your script performs on or with objects are called methods. These are functions built-into objects. Dealing with user-controlled events like clicks and mouse movement is accomplished through commands called event handlers. Together, these concepts form the basis of all JavaScript programming.
The DOM allows you to access these page objects. As mentioned above, for years there has been a bad situation wherein the two major browsers supported different versions of the DOM. Netscape's DOM was not compatible with Microsoft's, and so DHTML (Dynamic HTML) pages written to perform in one browser would not function in another. Recently, the W3C have standardised the model, creating the » DOM level 1. Rest easy however; unless you're planning on creating vast JavaScript-fuelled sites, this probably won't become an issue for you. Not yet anyway. We'll discuss the DOM in more depth in Objects and Properties.
Implementation
So how are we going to get our JavaScript into our pages? JavaScript is written in the same way as HTML — in a text-editor. JS implementation is quite similar to CSS; you can link to outside files (with the file extension .js
), or write blocks of code right into your HTML documents with the <script>
tag. The usual choosing criteria apply — if you're using the same script on many pages, link to an external file; otherwise embed.
We'll do our first example with an embedded script. This will simply print a line of text to the page.
<script type="text/javascript"> <!-- document.write("<i>Hello World!</i>"); //--> </script>
When you place that in your code the text Hello World will appear on your screen wherever you put it. Like so:
Let's break this down a bit. The script
tag encloses any script code you want to use. The type
attribute we have in there alert the browser to the type of script it is about to deal with (there are others, like VBScript), and so helps it to interpret the code.
The comments around the script code are there so that old browsers that don't understand the script
tag won't display the code as text on the page. Any browser that can do JavaScript will disregard the comments. Also note that for Netscape's benefit, the end of the comment is itself commented out using a JavaScript comment (two forward-slashes to comment out the rest of the line). This stops errors from occurring in old versions of Netscape.
External Scripts
To import scripts from external JS files, save the code in a text file with the .js
extension; without the script
tags and comments. In this case the code would just be the document.write("Hello World!");
part (although this won't do much on its own). We then link to this document, in the page's <head>
, with
<script type="text/javascript" src="simplemethods.js"></script>
Now all of the methods and variables that are in that file are available to use in the page. We'll learn more about that in the next tutorial.
Note that JavaScript Includes, like this, are not supported by Netscape 2 and Explorer 3. Also remember the end-tag. The usual abstraction benefits ensue: you can update that one script file and have all your pages change; and the script file is cached meaning it doesn't need to be downloaded again for each page that uses it.
We should always place includes in the head
so that the browser is ready to execute scripts when the user calls for them. If a user clicked a button that called for a script that the browser wasn't aware of yet, you'd get an error. Having them in the head
means they're always ready before they're needed.
A Simple Script
So what did our code above actually accomplish? Take another look at it.
<script type="text/javascript"> <!-- document.write("<i>Hello World!</i>"); //--> </script>
We start by taking control of the document
object, and use its write()
method to output some text to the document. The text inside the double quotes is called a String, and this string will be added to the page. Simple, right? To use an object's methods or properties, we write the object's name, a dot, and then the method/property name. Each line of script ends with a semicolon. JavaScript isn't very forgiving; if you make any mistakes in typing this out, you'll get a script error, so code carefully.
We'll do one more example before wrapping up for this tutorial. This script will create some HTML and text.
<script type="text/javascript"> <!-- document.write("<h1>Main Title</h1>"); document.write("<p align='right'>Body</p>"); //--> </script>
Note that when quoting attribute values, you have to use single quotes, as if you used double quotes the write
method would think the string was over prematurely, and you'd get an error.
<noscript>
The <noscript>
tag is a way you can give alternate content to browsers that don't support JavaScript or to modern users who have turned JavaScript off in their browsers. The way it works is simple: old browsers won't understand the tag and so ignore it and display whatever is inside it. Modern browsers will understand it and skip its contents. Use it like so:
<noscript>
<p>Sorry, your browser does not support JavaScript.</p>
</noscript>
You could also try to give something comparable to what the script is used to produce. In some cases no meaningful equivalent can be written for a JavaScript effect, and so any <noscript>
content will be redundant. However, you should always try and use this tag when appropriate — it helps keep your content accessible.