Javascript

What is Javascript?

Javascript is a scripting language, and here I will briefly explain how to integrate it into an HTMLHTML page. It is convenient because it allows us to interact with the user (HTML is completely passive).

NB: It has nothing to do with Java, it is not created by Oracle and it does not work with Java. The name comes mainly from the similarity between the syntax of the two languages.

Javascript

Javascript instructions are enclosed in the SCRIPT tag, like this:

<html>
    <head>
    </head>
    <body>
        <script type="text/javascript">
            instructions
        </script>
    </body>
</html>

 

Inserting comments

To insert a comment you can use two ways:

Single line:

// comment

Or multi-line:

/*
comment
more comments
*/

 

The alert function

It is used to display an alert message, but we can also use it for nonsense:

alert("Goo");

 

The write function

It must be used with the document instance and writes to the HTML page:

document.write("Text");

FAQ: Can I change the text style in the write function? Sure! Like this:

document.write("<p style='font-family:courier new;'>Text</p>");

You can use as many types of tags as you like.

 

The var statement

Declares variables:

var Variable;

To define it:

Variable = Value;

Value can be an integer or floating point number or a string (the latter goes in quotes).

Ex:

var a, b, c;
a = 3;
b = 5;
c = a * b;
alert(c);

We will see an alert message with the word 15 written on it. Here's what we did: we defined two variables, one with the value of 3 and the other with the value of 5, we then defined another one that has as its value an expression, that is a x b (3 x 5) and with the alert function we displayed the value of c.

The most important mathematical operators are:

  • + (plus)
  • - (minus)
  • / (divided by)
  • * (times)

This way you can create complex expressions.

 

The if statement

As in other programming languages, it executes a function if the condition is satisfied.

var a, b;
a = 10;
b = a / 2;
var c;
if (b == 5) {
    c = a / b;
} else if (a == b) {
    c = b * 2;
} else {
    c = a * 2;
}
alert(c);

Remember that the condition goes in round parentheses, while the conditional statements go in curly braces.

In questo caso la prima condizione viene soddisfatta, quindi visualizzerà il valore 2.

 

The prompt function

Asks a question and requests input.

a = prompt("What is your name?", "Name");
document.write("Welcome " + a + "!");

Name is the default input, i.e. a sort of example.

In the write function, the + is used to join the text with the value of the a variable.

Ex:

var a, b, c;
a = 1;
b = 2;
c = 3;
document.write("Variables are: a (" + a + "); b (" + b + "); c (" + c + ").");

Displays The variables are: a (1); b (2); c (3)..

 

The confirm function

It is used to give confirmation.

var a;
a = confirm("Do you want to answer the question?");
if (a == true) {
    var b;
    b = prompt("What is 1 + 1?");
    if (b == 2) {
        alert("Wrong! 11!");
    } else {
        alert("That's 2!");
    }
} else if (a == false) {
    alert("Ok, that's fine.");
}

NB: The margin spaces are there to avoid confusion and keep the code tidy, and there is no limit to the number of if statements that can be nested inside each other. Example:

var a = 2;
if (a == 2) {
    var b = 3;
    if (b == a) {
        var c = 5;
        if (c == a) {
            var d = 10;
            if (d == a)
                alert("How's that possible?");
        }
    }
}

Note that if there is only one conditional statement, there is no need to insert braces. Only the next statement will be conditioned.

 

The switch-case construct

Esegue delle istruzioni se la condizione sulla variabile è vera.

var a;
a = 3;
switch (a) {
    case "2":
        alert("a = 2");
        break;
    case "3":
        alert("a = 3");
        break;
    default:
        alert("a = " + a);
        break;
}

If the variable a is "2" it displays a = 2, if the variable a is "3" it displays a = 3, while in all other cases it displays a default message.

Quindi è analogo a:

var a;
a = 3;
if (a == 2) {
    alert("a = 2");
} else if (a == 3) {
    alert("a = 3");
} else {
    alert("a = " + a);
}

Note that in both cases the first two conditions fail because they are not of the same type. The comparative operator === specifies that equality must be respected without performing conversions between numbers and strings, differently from what we saw with the previous examples that use == (only two equal signs).

 

Various utilities

The length attribute

Returns an integer equal to the length of the variable.

var a = "Hello Foo";
document.write(a.length);

It will write 9.

 

The toUpperCase function

Returns the string in uppercase.

var a = "Hello Foo";
document.write(a.toUpperCase())

It will write HELLO FOO.

 

The toLowerCase function

Returns the string in lowercase.

var a = "Hello Foo";
document.write(a.toLowerCase());

It will write hello foo.

 

The replace function

Returns the string by replacing the specified word with another.

var a = "Hello Foo";
document.write(a.replace("Foo","Bar"));

It will write Hello Bar.

 

The split function

Returns the string replacing the specified character or characters with a comma.

var a = "Hello Foo";
document.write(a.split(" "));

It will write Hello,Foo.

 

The eval function

Returns mathematical value from a string.

var a, b;
a = '1';
b = 1;
document.write(eval(a) + eval(b));

I will write 2.

By doing so instead:

var a, b;
a = '1';
b = 1;
document.write(a + b);

I will write 11. In this case the variable b is converted to a string and the operator + corresponds to string concatenation instead of addition.

 

The function statement

Creates a function, i.e. a series of instructions to be executed using a keyword with possible arguments.

function a() {
    alert("Hi dude!");
}
document.write("<input type='button' value='Click!' onclick='a()'>");

So when the Click! button is pressed, Hi dude! will be displayed in a window.

 

The return statement

When inside a function, it returns the specified value:

function Multiply(a, b) {
    return a * b;
}
document.write(Multiply(3, 2));

This function performs the a times b operation. The value of the input variables will be determined only when they are specified during the function call.

 

Example of a function built in HTML

<html>
    <head>
        <style>
            body {
                font-family:"times new roman";
                color:#000011;
                bgcolor:#FFEEFF;
            }
            h2 {
                font-size:18px;
            }
            p {
                font-size:13px;
            }
        </style>
        <script type="text/javascript">
            function CheckThis() {
                if (document.f.b.checked) {
                    alert("Unfortunately not.");
                } else if (document.f.c.checked) {
                    alert("I'm not a millipede.");
                } else if (document.f.a.checked) {
                    alert("But at least that works!");
                }
        </script>
    </head>
    <body>
        <h2>How many fingers do I have on my hands?</h2>
            <form method="get" onsubmit="CheckThis()" name="f">
                <p><input type="checkbox" name="a" />Only one</p>
                <p><input type="checkbox" name="b" />Ten</p>
                <p><input type="checkbox" name="c" />A hundred</p>
                <input type="submit" value="Verify" />
            </form>
    </body>
</html>

You can see how document.f.c can be considered as a path that starts from the document and, like in a folder, you choose one of the possible objects belonging to the one of higher level, and their names are defined via name. checked is used to verify which of the boxes has been selected.

 

Two-addend calculator

<html>
    <head>
        <style>
            body {
                font-family:"times new roman";
                color:#000011;
                bgcolor:#FFEEFF;
            }
            h2 {
                font-size:18px;
            }
            p {
                font-size:13px;
            }
        </style>
        <script type="text/javascript">
            function calc() {
                var a, b;
                a = eval(document.tot.adda.value);
                b = eval(document.tot.addb.value);
                document.tot.res.value = a + b;
            }
        </script>
    </head>
    <body>
        <h2>Two-addend calculator</h2>
            <form name="tot">
                <p><input type="text" name="adda" /> + <input type="text" name="addb" /> = <input type="text" name="res" /></p>
                <input type="button" value="Calculate" onclick="calc()" />
            </form>
    </body>
</html>

Copy the code into a .txt text document, rename the file to .htm and open the file: here is the two-addend calculator!

 

ONCLICK event

As we saw before, it executes Javascript code or a function when the mouse clicks on the element of the tag where ONCLICK is specified:

<input type="button" value="Click here!" onclick="a()" />

Can be used in A and INPUT tags.

 

ONFOCUS event

Executes Javascript code if the text box is selected:

<input type="text" onfocus="a()" />

Can be used in SELECT, INPUT TEXT and TEXTAREA tags.

 

ONBLUR event

Executes Javascript code if the text box is deselected:

<input type="text" onblur="a()" />

Can be used in SELECT, INPUT TEXT and TEXTAREA tags.

 

ONMOUSEMOVE event

Executes Javascript code or a function if the mouse is moved within the tag object where ONMOUSEMOVE is specified:

<p onmousemove="a()">Hover here!</p>

Can be used in tags that create objects.

 

ONMOUSEOUT event

Executes Javascript code or a function if the cursor is moved out of the tag object where ONMOUSEOUT is specified:

<input type="text" onmouseout="a()" />

Can be used in A, INPUT, TEXTAREA tags and all clickable areas.

 

ONMOUSEDOWN event

Executes Javascript code or a function when a mouse button is pressed.

<input type="button" value="HELLO!!" onmousedown="a()" />

Can be used in BODY, A, INPUT BUTTON, INPUT SUBMIT and INPUT RESET tags.

 

ONMOUSEOVER event

Executes Javascript code or a function if the cursor is moved into the object of the tag where ONMOUSEOVER is specified:

<input type="text" onmouseover="a()" />

Can be used in A, INPUT, TEXTAREA tags and all clickable areas.

 

ONMOUSEUP event

Executes Javascript code or a function when a mouse button is released over the object where ONMOUSEUP is specified:

<input type="submit" onmouseup="a()" />

Can be used in A, INPUT BUTTON, INPUT SUBMIT and INPUT RESET tags.

 

ONKEYPRESS event

Executes Javascript code or a function if a character has been typed and displayed:

<input type="text" onkeypress="a()" />

Can be used in INPUT TEXT, TEXTAREA, A, BODY and IMG tags.

 

ONKEYDOWN event

Executes Javascript code or a function when any key is typed:

<input type="text" onkeydown="a()" />

Can be used in INPUT TEXT, TEXTAREA, A, BODY and IMG tags.

 

ONKEYUP event

Executes Javascript code or a function when any key is released:

<input type="text" onkeyup="a()" />

Can be used in INPUT TEXT, TEXTAREA, A, BODY and IMG tags.

 

ONRESET event

Executes Javascript code or a function when the INPUT RESET tag button inside the FORM tag is pressed:

<form onreset="a()">
<input type="reset" value="Reset!" />
</form>

Can be used in FORM tag.

 

ONSUBMIT event

Executes Javascript code or a function when the INPUT SUBMIT tag button inside the FORM tag is pressed:

<form onsubmit="a()">
<input type="submit" value="OK" />
</form>

Can be used in FORM tag.

 

ONSELECT event

Executes Javascript code or a function when text is selected in a text area.

<input type="text" onselect="a()" />

Can be used in INPUT TEXT and TEXTAREA tags.

 

ONDBLCLICK event

Executes Javascript code or a function when the element in the tag where ONDBLCLICK is specified is double-clicked:

<select size="3" ondblclick="a()">
<option value="food">Food</option>
<option value="blood">Blood</option>
<option value="brain">Brain</option>
</select>

Can be used in A and BODY tags, not available for Macintosh.

 

The INPUT TEXT tag

It is used to make the user enter text or input, it supports ONCLICK, ONDBLCLICK, ONSELECT, ONKEYPRESS, ONKEYDOWN, ONKEYUP, ONMOUSEMOVE, ONMOUSEOUT, ONMOUSEOVER, ONFOCUS and ONBLUR events. The result of:

<input type="text" name="one" />

will be:

Examples:

<html>
    <head>
        <script type="text/javascript">
            function f() {
                document.one.in.value = "Focus acquired";
            }
        </script>
    </head>
    <body>
        <form name="one">
            <input type="text" name="in" onfocus="f()" />
        </form>
    </body>
</html>

So when you get focus (i.e. when the cursor starts flashing) the bar will display Focus acquired.

 

<html>
    <head>
        <script type="text/javascript">
            function b() {
                document.et.chuck.value = "Focus disabled";
            }
            function f() {
                document.et.chuck.value = "Focus enabled";
            }
        </script>
    </head>
    <body>
        <form name="et">
            <input type="text" name="chuck" value="Focus disabled"; onblur="b()" onfocus="f()"/>
        </form>
    </body>
</html>

This way when the focus is active it displays Focus enabled, when it is inactive it displays Focus disabled.

 

<html>
    <head>
        <script type="text/javascript">
            function lol() {
                alert(document.hey.goofy.value);
            }
        </script>
    </head>
    <body>
        <form name="hey">
            <input type="text" name="goofy" value="Value123" onclick="lol()" />
        </form>
    </body>
</html>

When you click on the bar, it displays the value of the bar in an alert window.

 

<html>
    <head>
        <script type="text/javascript">
            function x() {
                a = prompt("Write the value to give to the bar","");
                document.four.cats.value = a;
            }
        </script>
    </head>
    <body>
        <form name="four">
            <input type="text" name="cats" ondblclick="x()" />
        </form>
    </body>
</html>

Double clicking on the bar will prompt you to enter the value that will then be given to the bar.

NB: If you click Cancel, null will be given as value.

 

<html>
    <head>
        <script type="text/javascript">
            function s() {
                alert("You have selected something");
            }
        </script>
    </head>
    <body>
        <form name="nome">
            <input type="text" name="input" onselect="s()" />
        </form>
    </body>
</html>

When something is selected from the bar it will display a warning message.

 

INPUT BUTTON tag

Creates a button, it supports ONCLICK, ONMOUSEDOWN, ONMOUSEUP and ONMOUSEMOVE events. The result of:

<input type="button" name="one" value="Click!!" />

will be:

Example:

<html>
    <head>
        <script type="text/javascript">
            function c() {
                alert("Do you want applause?");
            }
        </script>
    </head>
    <body>
        <input type="button" value="Click!!" onclick="c()" />
    </body>
</html>

Clicking Click!! will display a warning message.

 

INPUT SUBMIT tag

Creates a button, it supports the ONCLICK event, but is not very useful. Must be inside a FORM, the ONSUBMIT event can be inserted in the FORM tag.

Example:

<html>
    <head>
        <script type="text/javascript">
            function s() {
                alert("The name of the bar is: " + document.c.o.name);
                alert("The value instead is: " + document.c.o.value);
            }
        </script>
    </head>
    <body>
        <form name="c" onsubmit="s()">
            <input type="text" name="o" />
            <input type="submit" value="Go" />
        </form>
    </body>
</html>

Clicking Go displays the name and value of the text bar in two alert windows.

 

INPUT CHECKBOX tag

Creates a checkable box. To make it checked by default on page load add CHECKED. It supports the ONCLICK event. The result of:

<p><input type="checkbox" name="one" />Knave</p>
<p><input type="checkbox" name="two" />Knight</p>
<p><input type="checkbox" name="three" checked />King</p>

will be:

Knave

Knight

King

Example:

<html>
    <head>
        <script type="text/javascript">
            function j() {
                if (document.gh.stron.checked) {
                    alert("One");
                }
                if (document.gh.strtw.checked) {
                    alert("Two");
                }
            }
        </script>
    </head>
    <body>
        <form name="gh" onsubmit="j()">
            <p><input type="checkbox" name="stron" checked />One</p>
            <p><input type="checkbox" name="strtw" />Two</p>
            <input type="submit" value="    OK    " />
        </form>
    </body>
</html>

There are two CHECKBOXes, of which One is already selected. If One is selected when clicking OK, an alert box will pop up with the message One. If Two is selected, an alert box will pop up with the message Two. If both are selected, two alert boxes will pop up, one saying One and the other saying Two.

 

INPUT RESET tag

Creates a button: when pressed it restores the FORM data. This means it must be inside the FORM tag. The result of:

<form name="form">
<p><input type="checkbox" name="one" />Knave</p>
<p><input type="checkbox" name="two" checked />Knight</p>
<p><input type="checkbox" name="three" />King</p>
<input type="reset" value="Reset!" />
</form>

will be:

Knave

Knight

King

Example:

<html>
    <head>
        <script type="text/javascript">
            function j() {
                if (document.gh.stron.checked) {
                    alert("One");
                }
                if (document.gh.strtw.checked) {
                    alert("Two");
                }
            }
       </script>
    </head>
    <body>
        <form name="gh" onsubmit="j()">
            <p><input type="checkbox" name="stron" checked />One</p>
            <p><input type="checkbox" name="strtw" />Two</p>
            <input type="submit" value="    OK    " />
            <input type="reset" value="Reset" />
        </form>
    </body>
</html>

 

INPUT RADIO tag

Creates a selectable circular element. To make it selected by default, add CHECKED. It supports the ONCLICK event. Very similar to the CHECKBOX, but with the difference that it cannot be deselected by the user, and it does not allow selecting more than one option within the same form. The result of:

<p><input type="radio" name="one" />Knave</p>
<p><input type="radio" name="two" />Knight</p>
<p><input type="radio" name="three" checked />King</p>

will be:

Knave

Knight

King

Example:

<html>
    <head>
        <script type="text/javascript">
            function glo() {
                if (document.o.c.checked) {
                    alert("One");
                }
                if (document.o.i.checked) {
                    alert("Two");
                }
            }
        </script>
    </head>
    <body>
        <form name="o" onsubmit="glo()">
            <p><input type="radio" name="c" />One</p>
            <p><input type="radio" name="i" />Two</p>
            <input type="submit" value="    OK    " />
            <input type="reset" value="Reset" />
        </form>
    </body>
</html>

NB: The default value of SUBMIT is Submit Query, while the default value of RESET is Reset.

 

The SELECT tag and the OPTION tag

The SELECT tag creates a box where you can choose various options (OPTION tag). To select a default option just add SELECTED. It supports ONCLICK, ONFOCUS, ONBLUR and ONDBLCLICK events. The result of:

<select name="selection" size="1">
    <option name="one" selected>Knave</option>
    <option name="two">Knight</option>
    <option name="three">King</option>
</select>

will be:

Example:

<html>
    <head>
        <script type="text/javascript">
            function fu() {
                if (document.sel.fi.selected) {
                    alert("First");
                }
                if (document.sel.se.selected) {
                    alert("Second");
                }
                if (document.sel.th.selected) {
                    alert("Third");
                }
            }
        </script>
    </head>
    <body>
        <p><select size="3" name="sel">
            <option name="fi" selected>First</option>
            <option name="se">Second</option>
            <option name="th">Third</option>
        </select></p>
        <input type="button" value="Go" onclick="fu()">
    </body>
</html>

Clicking Go will display your choice in a pop-up window.

 

TEXTAREA tag

It is the same as INPUT TEXT, but by default it is larger and has a different font. The result of:

<p><textarea name="one">You are crazy</textarea></p>

will be:

To change height and width:

<textarea rows="" cols=""></textarea>

On ROWS write the rows and on COLS the columns.

Comment below if you have any questions.

Comments