Displaying output
To displayoutput at a specific place on the webpage, put a
‘bookmark id’ into the body of the html code, where the output
needs to be displayed:
<body>
...
<h2 id="Output here"> </h2>
...
</body>
3.
Displaying output (2)
◦The id= “Output here" bookmark is in the body of the html, not the script section
so the html comment syntax is used
◦ The id is in style h2 so the result of the script will be displayed in style h2.
Setting the value of a .innerHTML property using the
document.getElementById() method enables us to place results at a
bookmark inside a webpage:
◦ document.getElementById("Output here").innerHTML = 5 + 7;
◦ document.getElementById("Output here").src =“example.jpg”;
4.
Function
A JavaScript functionis a block of reusable code designed to perform a particular task.
Functions can be called anywhere in a script, and any number of times. Creating a
function means that the code does not have to be rewritten every time. Functions also
allow programmers to divide long scripts into a number of small and manageable
routines.
function name (parameter1, parameter2, … )
{
code statements to be executed;
}
5.
Function (2)
Variables thatare available only within a function are local variables.
Variables that can be used in other functions or other parts of the script
are global variables. Global variables need to be declared without the
‘var’ keyword. Here, value1 is declared as a global variable in
input() so that it can be used by the function output():
◦function input(){ value1 = 1; }
◦function output(){alert(value1); }
▪If var value1 had been used, this would declare a local variable and
value1 would not be available for the output()function to use.
▪In fact, variables can always be declared in this way. You just need to
be careful about whether you need local or global variables.