Jegsworks: Free Online Computer Lessons Logo:Jegsworks Jan's Illustrated Computer Literacy 101

Home > Resources & Examples > Jan's Web Scripting Demo > JavaScript

Icon: Arrow - Previous pagePrevious    NextIcon: Arrow - Next page

Jan's Web Scripting Demo: Javascript

JavaScript is a programming language that is commonly used to write scripts for controlling what shows on a web page and for creating ways for the user to interact with the elements on the page.

A statement is a single command in a script. It must be a single line of code.

A function is made up of one or more statements. A function can be called or invoked in response to an action or event, like when the page loads or when the user clicks on an object.

The statements in the function are executed in the order they are listed unless there are alternates based on criteria. For example, if a comparison is true (x > 0), do one thing (write the word "positive"). Otherwise do a different thing (write "negative or zero").

A script is a set of statements and functions. Any statements that are not part of a function will be executed when the browser reads the page. These usually set initial values for variables that will be used later or pre-load images. A function will not execute until it is called.

This page will introduce you to some features of JavaScript, just enough to help you understand the scripts in the examples.

Example: Change Image

Vehicles galore - how many can you identify? Click the picture to see answers.  
Click the image to show an image with labels.
Click again to return to original.

[This image is also used in Computer Basics:Lessons:Lesson 1:Computer TypesIcon: In site]

To make the image change requires three parts:

  • ID for the image, id="vehicles" in the IMG tag
  • Script defines one or more functions that change the source for the element with id="vehicles". This script is in the HEAD section of the page.
  • onClick attribute for the image calls the proper function, changeimage()
//Switches image of vehicles to a different version or returns to original image

var countclicks=0;                     //Initialize a counter when the page loads

function showlabels()
{countclicks=1;                        //Increase the counter
                                            //Changes the source for the image
function showvehicles()
                                           //Returned the image to the original source file
countclicks=0;                       //Reset the counter to zero
function changeimage()         //Pick which function to use
{if (countclicks===0) {showlabels();}
else {showvehicles();}

The script above is one of many ways to accomplish the same effect.

Where do you put the script?

  • External File: If your scripts can be used on many pages, you can create a separate document that contains the lines of code and point to it its location in the HEAD of each page, like <script src="../scripts/myfirstscript.js"></script>. In this case there cannot be anything between the opening and closing SCRIPT tags. An external JavaScript document does not contain SCRIPT tags itself, just the JavaScript code.
  • On the page in HEAD or BODY: Between SCRIPT tags, like:
function showtext()
{document.getElementById('mytext').innerHTML="This was created by my script";
  • Inline: A short script can be written inside a tag with an event attribute, like
    <p onClick="'targetpage.htm', '_blank')">Click me</p>

    Try it by clicking the code line above to open the page in a new window or a new tab, depending on your browser's settings.

    Writing script inline is not recommended! It is hard to find on the page. It is hard to read and edit, which makes it easy to make mistakes.


Like any other programming language, JavaScript is picky about the syntax of what you write. JavaScript syntax include rules about spelling, capitalization, and punctuation. If you omit a comma or a semicolon or a brace or misspell a property name, the whole process may stop dead or (even worse!) give incorrect results.

Tips about JavaScript Syntax:

  • Names (identifiers):
    Must be unique within the current page.
    So, you cannot have two DIV tag with id="comment" on the same page. You cannot have two diffeernt functions named MyFunction() available to the same page, even if one is in the HEAD of the page and the other is in a external script. Of course, a function might be called from many different places on the page. But, a particular function can be defined only once.
  • Characters allowed:
    A name can contain letters, digits, underscores, and dollar signs, but cannot begin with a number. No spaces allowed.
  • Names are case-sensitive:
    function myText() and function MyText() are two different functions.
    firstname and firstName and FirstName are all different element IDs.
  • Single line:
    Each statement in a script must be on a single line and finish with a semicolon, (;). Word wrapping can be used for convenience in a text editor. Turn off word wrapping to check that the statement does lie on a single line. (This is a common source of errors for people new to programming.)
  • Text values:
    Enclose text values in quotes or double quotes, like "Fred" or 'Los Angeles'.
    var x = Smith means the new variable x is assigned the same value as the object Smith.
    var x = "Smith" means the new variable x is assigned the text value "Smith".
    var x = 4 means the new variable x is assigned the numerical value 4.
    var x = "4" means the new variable x is assigned the text value "4".
  • Comments:
    Anything on the same line after a double slash // in a script will be ignored. You can use this to write short comments.

Writing JavaScript Statements

  • New variable:
    Identify a new variable with var the first time it appears in the script.
    var apples = 8;
    var oranges = 9;
    var totalfruit = apples + oranges
  • Assigning values:
    Assign a value to a variable with =, as in algebra:
    var x = 4;
    var y = 8;
    var z = x * y/2;
    var mytext = "My car is old"
  • Comparing values:
    When checking to see if a variable is equal to a value or another variable, use three equal signs, like x===maximumAmount, which compares the data type also.

    If you use two equal signs, like y==0, the comparison will be 'true' if y is equal to the number 0 or to the Boolean value False or to the empty string
    "". It is a subtle difference that sometimes makes a big difference!
  • Arithmetic operators, + - * /:
    Use the order of operations from algebra.
    Calculations in parentheses are done first. Operations are done from left to right with functions done first, then multiplication and division from left to right and then the addition and subtraction from left to right.

    You Do It: Calculate:   
    x = 4 + 7 * 3 - 5 Show answer
    y = 7 + (8 - 3 * 8) / 4 Show answer
    z = 6 * 7 - Math.pow(8,2) + 5 Show answer

  • Concatenate:
    Use + to combine literal text (in quotes or double quotes) with variables.

    function createtext()
    {var firstname=document.getElementById("fname").value;
    var lastname=document.getElementById("lname").value;
    var score=document.getElementById("testscore").value;

    document.getElementById("newtext").innerHTML="The score for "+firstname+" "+lastname+" is "+score+"."

    which produces a sentence like, 'The score for Jan Smith is 98' or 'The score for Mark Johnson is C', depending on the values for the three variables, firstName, lastName, and score. The " " adds a blank space between the first and last name. Note that " is " includes a space before and after the word is.

    Try It:

    Fill in the name and score of your choice. Click the button Concatenate to create a new sentence below the button.


Writing JavaScript Functions

  • Define a function:
    A simple function looks something like:
    function MyFunction() { ...commands go here...}
    The word 'function' is required. Then write the name of the function and two parentheses. The actual commands you want to be executed come next, between two curly brackets, { and }, also called braces.
  • Functions that accept values:
    Write a placeholder name inside the parentheses of your function for the values that the function will use. Use the placeholder names in the commands.
    function FullName(first,last)
    {var employeeName=first + " " + last;} //concatenates

    In the web page you could call this function like onClick="FullName(fname,lname);"
    If fname has value "Jan" and lname has value "Smith", then the function assigns to the variable employeeName the value "Jan Smith".

    function myFunction(a,b)
    {return a + b;}            //Returns the sum of a and b

    In the web page you could call this function in different places and write different values, like onClick="myFunction(4,5)" would produce 9. But in and in another place onClick="myFunction(6,7)" would produce 13.

Calling a JavaScript Function

A JavaScript function is called or invoked by an action like onMouseOver or onClick or by an event like onLoad or onChange.

<body onLoad="myFunction()">

<p onClick="showtext()">Click here to show text</p>

<div onMouseOver="replaceme()>