The two technologies we have looked at already allow us to create documents which have content and a structure, and can be styled according to a particular design.
But aside from clicking on links and submitting data into a form, what else can you do with a webpage?
With HTML and CSS not much else. To make web pages more interactive, we need to be able to make use of a third technology: Javascript.
Document Object Model
Before you can make use of Javascript, you need an understanding of the underlying representation of a web page inside the web browser using something called the Document Object Model (DOM).
The web page as specified in the HTML and CSS, is represented by elements, attributes and text within the DOM.
These items can all be manipulated by Javascript code which can read or change values within the DOM and therefore can change the page itself.
Event driven programming
Javascript programming is very different to what you have been used to when writing Java or Python programs. Program fragments have to be triggered by things called events.
An event could be:
- Clicking on a button
- Moving the mouse over an image or text
- Loading or refreshing the web page
- Dragging an element on the page somewhere
In this paradigm, events trigger event handling functions written by the programmer. For example,
<button onClick="myFunction()">Click me!</button>
Often in Javascript code, an event triggers code which will alter the content on a web page, or read some content from the web page.
The web page here contains a single HTML element (an image) plus two buttons. Clicking either of the buttons changes the value of the src attribute of the image, so alters the page to display a different image.
<html>
<body>
<div style="text-align:center">
<button onclick="document.getElementById('theImage').src='up.png'">Up arrow</button>
<img id="theImage" border="0" src="up.png" style="width:50px">
<button onclick="document.getElementById('theImage').src='down.png'">Down arrow</button>
</div>
</body>
</html>
Creating the code
Javascript can be included on a web page by enclosing it between <script> tags.
It is normal to put the script near the bottom of the web page so the HTML is read by the browser first, and the script last.
Script can also be put into an external file just like CSS can –for more complex pages this is preferable than keeping it in the HTML as it can be reused in other web pages:
<script src="script.js"></script>
Javascript syntax
It is worth saying at this point that Javascript is not the same thing as Java. They are different languages with different purposes and underlying technology. However the syntax is very similar:
Blocks of code are started and ended with { }
Each line ends with a ;
Selection structures such as if and else, are the same as in Java.
if (guess>number){
console.log("too high");
}
else if(guess<number){
console.log("too low");
}
else if (guess===number){
console.log("got it");
}
There are some differences too:
Variables don’t have a datatype, so if you want to check that the value is the same and the datatype is the same, you need an extra = sign
if ( a == 2 ) // a needs to contain 2 and the datatype doesn't matter
if ( a === 2 ) // a needs to contain 2 and be a number not a string
if ( a != 2 ) // a needs to contain anything but 2 or "2"
if ( a !== 2 ) // a needs to contain anything but the integer value two
If you’re not familiar with Java, note that OCR exam answers often require the use of logical and as well as logical or so you will need to remember the syntax for both:
OR in Javascript is || (the pipe character, twice)
e.g.
if (day =="Wednesday" || day =="Thursday")
AND in Javascript is && (the ampersand character, twice)
if (lives > 0 && quit == false)
Code is nearly always declared within a function, and as we said earlier, can be embedded within a web page inside <script> tags:
<script>
function myFunction(){
console.log("I’m running a script!");
}
</script>
The console.log() function can be used alongside the console window in your browser which is normally not visible but can be turned on, usually by selecting “developer tools” or something similar (keyboard shortcut CTRL-SHIFT-i). It is used in a similar way to print statements to debug code by outputing the values of variable or messages as the program runs.
The developer tools display may also show you errors with your HTML or Javascript, usually in a debugger window.
Interacting with the DOM
To get or set elements on a page, we use the ID of the element, and a DOM method called getElementById()
To set an element to a particular value, for example to make some text appear in a particular place on the page, we can do this:
document.getElementById("message").innerHTML="Hi!";
To get something that is on the page, for example text typed into a text box on the page, we can do this:
var name=document.getElementById("textbox").value;
Note the camel case especially the lower case d in Id – a common source of errors as it is tempting to write ID!
Activity 1
Create a new web page containing the following:
- A paragraph with ID “outMessage”, initially containing the text “type your name and then click the button”
- A text box for input, with the ID “textIn”
- A button to trigger the Javascript called “Say Hello”
- A script block containing a function called sayHello()
- Add code into the function that gets the value typed into the text box and stores it in a variable called name. Print the value to the console.
- Add code into the function which changes the innerHTML attribute of the outMessage paragraph to say “Hello “ followed by the name stored in the name variable.
Activity 2
There are a huge number of in built library functions in Javascript. A useful one is the random number generator within the Math library:
var number=Math.floor(Math.random()*6);
Create another blank web page that generates a random number and outputs it onto the browser console windows when a button is clicked.
High – low game
You should now be able to take what you have learned so far to create a simple game that generates a random number and asks the player to guess it. The game lets the user know whether their guess is too high, too low, or guessed correctly.
- Have a button labelled “Start game” which when clicked, generates a random number for the user to guess from 0 to 100.
- Have a paragraph with ID “responseBox” where the program tells the user whether the number guessed is too high or low.
- Have a paragraph with ID “instructions” where the program tells the user to click the start button or to guess a number.
- Have another button, called “Guess”
- Have a text box called “guessIn” into which the user enters their guess.
- The program should have code that alters the responseBox text to say “Too High”, “Too low” or “You guessed it!” as appropriate
Test your game!
Knowledge Check
- What is the purpose of Javascript within a web page?
- What is the role of the DOM?
- How do you link a button on a page to a piece of code in Javascript?
- How can you read the value typed into a textbox into a Javascript variable?
- How can you change a paragraph of text in a web page to display different text as a result of some Javascript code being triggered?