Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

MANG6531 Managing Digital Design and Web

Development Computer Lab Session 1: HTML & JavaScript

One of the learning outcomes of MANG6531 (Managing Digital Design and Web Development) is that you develop some basic web scripting skills to gain a better understanding of the design decisions and complexities involved in web development.  The three computer lab sessions on the module are designed to kick-start this learning process; in addition, by providing pointers to a number of valuable self-learning resources, they should also help you to extend your learning as you work your way through the individual scripting assignment.

To understand how web applications are built and engage in basic development activities yourself, it is essential you understand the difference between client-side and server-side technologies (also further covered in our second lecture).

Client-side technologies are those that are interpreted or run at the user's end (i.e. the client’ computer).  For example, a web developer may use HTML to specify the contents of a web page; each time a visitor then accesses that page and the corresponding HTML document is downloaded to their computer, it is rendered by that visitor's browser (e.g. Chrome or Firefox) into an easily readable form.  Hence, HTML is considered a client-side technology as HTML content is processed by the browser.   Similarly, a web developer could also decide to add JavaScript code to that same web page, so as to embed some user-side functionality into the page, e.g. by including a script that calculates the total order price based on whichever options the  user has selected so far on the  page.   JavaScript thus  presents another client-side technology, as, in the given example, the price calculation functionality can again be run entirely by the browser.

In contrast, server-side technologies are used by web developers to implement functionality that runs on the web server itself (not the browser!).  For example, when you access a product page on an online retailer's website, this page was most likely produced on the fly by a server- side script or program running on the server that looked up the product details on a database server and produced a HTML document based on the latest details found there.  Similarly, a server-side script may be required to send user data back to that database (e.g. account registration information, order details, etc.).  Several competing server-side technologies have emerged over time, but, on this module, we will pick out PHP.

Whereas next week's computer lab class will introduce you to server-side scripting and PHP in particular, this week's lab class will focus on two client-side technologies HTML and JavaScript.  The main aim of this first session is to let you experiment with HTML/JavaScript coding so as to:

•    Familiarise yourself with creating HTML documents and HTML forms;

•    Gain a basic understanding of the JavaScript language and how it can be used to embed client-side functionality into HTML documents.

To create the suggested HTML/JavaScript documents, you can in theory use a simple text editor such as Windows Notepad.   However, you will find it much easier to avoid mistakes using a dedicated editor. I suggest you use Sublime Text, an enhanced text editor for Windows, Mac etc which offers some useful features for source code editing such as tabbed editing (to easily work on multiple files), syntax highlighting for PHP, JavaScript, etc.

The following activities are designed to get you started but next you will have to do some more independent learning.  To help you learn more about HTML, note that there are good HTML tutorials available on the Web, e.g., onwww.w3schools.com, which you can use as a step-by- step  introduction  or  to  look  up  certain  language  elements.  Also, www.codecademy.com provides a fun and interactive way of learning JavaScript. None of these sites require any prior programming experience! These and other useful links are available in the Web Links” section on the module's Blackboard site.

Activity 1: Creating a HTML document; HTML tables and forms

Let's start by creating a simple HTML page from scratch.  Start Sublime Text application, and enter the following markup code:



Activ. 1: Creating HTML documents; HTML tables and forms



Welcome to our online shop



Please specify your order.




Make sure you don't misspell any of the HTML tags (i.e. the keywords surrounded by the “<” and “>” symbols) – they have to be exactly as shown above!

After you finished typing your document, save it as a HTML document.  To do so, select “File – Save As...” from the menu, select the My  Documents” or Documents” folder on your computer, and give your document a meaningful name followed by the .html file extension (e.g. name it Activity1.html”).1   Click the Save” button.  You can leave Sublime Text application open by the way as we will be making some changes to the document later on.

If all went well, you have just created a basic HTML page.   Let's test whether that page is shown correctly in your Web browser. Open the folder on your computer and find the file you just created.  Double-click it.  The page should now be opened in the default browser on your system (e.g. Internet Explorer, Firefox, or Chrome).  Check whether it displays correctly we would like it to look something like this:

If things are missing or some markup is accidentally shown, you probably made a typo.  Go back to correct if necessary, using Sublime Text.   Note: if nothing is showing at all in the browser, you probably made a mistake high up in the document, whereas if e.g. the second sentence is not rendered correctly, the error might be located between the first and second sentence. Sublime Text may help you locate errors more quickly by highlighting or underlining HTML syntax errors.

Let's have a closer look now at the HTML document you just created.   HTML documents typically include two main sections: the header section (starting withand ending with) and the main body (starting withand ending with).

<body>

<h1>Welcome to our online shoph1>

<p>Please specify your order.p>

</body>


In the header section, one of the things you can declare is the title of the document with some browsers, this will be shown in the title bar at the top of the browser window.  To specify a title, you include it in between a and tag, inside the header section.

In the subsequent body section, you can specify the visible content that must be shown inside the browser.  Most of what you typed here is plain text.  However, by placing some of this text between some pre-defined opening tag and closing tag, you can indicate how you would like that particular text part to be formatted.  For example, by putting

and

around a piece of text, you are asking for it to be formatted as a level-one header (usually shown in a large bold-face font), whereas the

and

tags e.g. delineate the start and end of a text paragraph.  Note how a forward slash (“/”) is inserted into a tag to indicate it's a closing tag (that is, it indicates where the formatting is supposed to stop).


HMTL defines a whole range of different tags that you can use to specify content, and have it formatted the way you like.  It's just a matter of looking up the right one.  The vast majority of these tags come in pairs an opening tag and a closing tag.  So don't forget to close a section you started!

Let's go back to editing our Web page in Sublime Text and add some more content.

Say we want to add a footer section that contains a link to the shop's privacy policy. To create such a link, we use the HTML tag (the a” stands for anchor”).  Since we would like the link to be shown at the bottom of the page, insert the following markup code just before the end of the body section:


Privacy Notice


As a result, you should now have the following markup code:



Activ. 1: Creating HTML documents; HTML tables and forms



Welcome to our online shop



Please specify your order.



Privacy Notice




Save your document. Double-click on the updated HTML-file to present it to the browser. Your page should now be displayed as follows:

Notice how the link you just added has been formatted.   Try clicking on it.   Of course, we haven't actually created the Privacy.html” file yet so at this stage this will simply produce a “File not found” error.

Let's have a closer look at how this link was encoded in HTML. Again, we find that there is an opening tag () and a closing tag ().  The text description we want to be shown in the browser (here: “Privacy Notice”) we put between those two tags.  What is new though is that the tag also includes a HTML attribute: href.  In general, an attribute is used to specify additional   information  about  the  content,  style   or  some  other  characteristic   of  the corresponding HTML element.   A value for the attribute is specified after the equal sign . In this case, the href attribute specifies the URL for the link, i.e. the address where the privacy notice  is  located.    By specifying Privacy.html”  as the value for the  href attribute, you effectively say the link should point to a HTML file with that name, and as no path is specified that file is assumed to be located in the same folder or directory as the referring document. So let's create a second file called “Privacy.html” following the procedure you learned earlier. This second document could e.g. consist of the following markup code:



Privacy Notice




Privacy Notice



Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.




Save the document and now reopen or refresh your first page in the browser and click on the link again.  This should now take you to this second document.

The next thing we'll add to our first HTML page is a basic form section in which the visitor will be able to enter their details and payment method.  HTML forms provide tag-based interface objects called input elements (for example, text boxes, selection lists, radio buttons, etc.) to enable the user to send data to the server.  Try adding the following form section into your page's body section – make sure you slot it in at the right location (inside the body, in between the “Please specify …” paragraph and the footer):




Your name:



Street address:



City, postcode:



Payment Method:




checked = "checked"> Visa

Master Card








Save and open the file again in your browser.  Your page should now look as follows:

Let's further examine this form section and its input elements.  The form section starts and ends with the

andtags, respectively.  Two of the attributes included as part of the form tag are:


•    action: used to specify which server-side script to run if the user clicks the submit order button we'll be learning more about this in next week's session, so for now we leave it empty ("");

•    method: the HTTP request method (GET or POST).

The other important tags in a HTML form are those that define the input elements.  These do not come with a separate opening and closing tag but just one tag, , which typically includes at least the following attributes:

•    type: specifies the type of input element; is it a text field, password field, radio button, checkbox, submit button, etc.?

•     name: each element is usually given a name so that the value entered by the user can be accessed in a script (see later); when you're adding a series of radio buttons, giving them the same name also allows you to specify that the options are mutually exclusive

– ticking one option will then untick the others.

Go through all the elements of your form section and make sure you understand the various tags and attributes used.  Experiment a bit by making a few changes and inspecting the effects of those changes.

Note that a useful explanation of the most popular HTML form elements can be found at http://www.w3schools.com/html/html_forms.asp.   Have a quick look at what information is included there.2

At this point, we have not yet included a list of products that can be ordered from our shop. Clearly, in a real-world scenario, we would not be hard-coding this into HTML but instead fetch this information at run-time from a database containing our product catalogue.  This is what we'll do in next week's lab session.  However, let's keep things simple for now and define a HTML table listing the three products below:

This table should consist of four rows and three columns.   The first row is a header row (consisting of column headers shown in bold); the next three rows are data rows.  The third column should include (empty) text input fields in rows 2-4 to enter the order quantity.

Look up the HTML table syntax at http://www.w3schools.com/html/html_tables.asp and take some time out to try and write your own markup code to produce the table above!

Next, check your solution.  Does it correspond to the markup shown below?






































Product Name Price Quantity
Record Cleaning Brush £12.20
Record Cleaning Cloth £2.40
Anti-Static Gun £72.00


Activity 2: hello world” JavaScript

Start a new HTML file (e.g. “Activity2.html”). Recall that your file will need a header and a body section.  Include the following JavaScript function inside the…section:



Look at the structure and syntax of this code snippet.  It defines a function which when called upon will show an alert box with the message Hello world!” inside. At this point, we have only “declared” the function we haven't yet made clear though when it should be executed.  So absolutely nothing will happen yet if we would open this page in the browser.  Say we'd like to bring  up  the Hello  world!”  message  whenever  the  user  clicks  on  a  certain  button. To do so, add a HTML form section (

...
) to the document's body (i.e. include it inside the…section) in which you put the following button control:


We have encountered the input tag and its type and value attributes in the previous activity, so nothing new there. What's new is the onclick event attribute which is used to specify what Javascript code snippet to run when the corresponding button gets clicked.  In this case, we have specified that the showHelloWorld function defined earlier should be called.  Make sure you use the same capitalisation (e.g. small s, capital H) as JavaScript is case-sensitive!

Your code should now look as follows:



Activity 2: hello world JavaScript















Save it and try it out in your browser.  Each time you click on the button, the function defined earlier will be invoked, and a hello world” message should pop up as a result (see below).

This is a simple example that illustrates how JavaScript can be used: to provide some form of user interaction or client-side functionality on what would otherwise be a static HTML page. This can be done by defining one or more functions that are called in response to some user interface event(s) (e.g. the clicking of a button, the mouse hovering over a certain area, a drag/drop event, etc.). Just as with any other programming language, the JavaScript code that you write must follow the syntax rules of that language.  This is beyond the scope of this first introduction, but e.g. the script itself or selected statements within that script are enclosed between “{“ and “}”, statements are followed by a semi-colon (“;”), etc.

In our example script so far, the same message is always shown (“Hello world!”).   But the functionality encoded in a JavaScript can just as well depend on what the user has entered or what has gone on so far on the page.  Say for example that you would like the message to be different depending on what name the user has entered into a text field on the page.

First we need to add that new text input field to the form section, e.g. by inserting the following line of HTML code:


Enter your name:


The id attribute in the line above assigns a unique name or identifier (ID) to the newly added input element.  We will later use this ID to access that specific input element from within our JavaScript code.  You could as well give it another ID as long as you use the same one later.

Next, we want to add a second function to our script, and include another button to invoke it. This new function should look up the name the user entered in the text field (e.g. in the screenshot below, the user has just typed Peter”), and then show a personalised greeting (e.g. “Hello Peter”).  In other words, what we're aiming for is something that will look like this:

Before we can start writing this function, we first need to have a basic understanding of how JavaScript can interact with the HTML elements on a page through what we call the DOM (Document Object Model). Typically, the DOM takes the form of an object hierarchy which can be traversed to get you to the HTML element you're looking for.  When writing your script, you can access the root of this tree using the document object. This object simply represents your HTML document.  In order to then access the text input element where the user will enter their own name, you can use the getElementById method of the document object.3    Just provide it with the unique ID of the HTML element you're looking for (here: “txtyourname”) and it will navigate through the DOM to find the HTML element whose id attribute matches the ID you specified.  If you have never programmed before, this will probably not make a great deal of sense yet, so let's first write the code, try it out, and then examine it again.

Starting from the HTML document you have so far, add in the bits in yellow so that you end up with the code shown below.  Save the file.



Activity 2: hello world JavaScript

3   Note that there are several alternative ways to access  DOM elements  (e.g.  based on  the  name attribute),  with  varying  degrees  of  support  by  various  specifications  (e.g.  XHTML)  and  browser implementations; I would recommend you use this one though (i.e. based on the id attribute) to try and ensure your solution works on all browsers.














As soon as you are ready, open the file in your browser (or refresh if it's still there).  Try your new code out.  If you type your own name in the text box and click the Hello you” button, do you get greeted by your own name?  If not, you made a typo somewhere and you have to go back to correct it.4

Let's examine the code in more detail now.  The two new bits in the body section should be pretty straightforward: they add a text box and an extra button to your page.  Note that this second button is linked to a function called showHelloYou” .  This new function is included, alongside the function declared earlier, in the header section of the document.  It contains a single statement:

alert("Hello " + document.getElementById("txtyourname").value);

Like earlier, alert() is just a pre-defined function we're using to bring up a message box. That function takes an argument (parameter) that specifies what message should be shown (note that function arguments are always put between parentheses). For the function we wrote earlier in the exercise, this was a simple text string, “Hello world!” .  Now it is a string that is formed out of two parts: “Hello ”, directly followed by whatever text the user entered into the text box.  The “+” operator is what concatenates these two strings into one text string.  Take a closer look at how the script is able to make out what the user has entered into the input box. It does so using the document object and its getElementById() method (see earlier).  Think of this method as a service that the document object provides for you: to fetch you the right HTML object based on the ID you present it with.   Here, “txtyourname” is specified as an argument so this is the ID that the method will be looking for.  What does our script then do with this object?  It looks up the value of one of its attributes. We have seen before that HTML elements can have attributes (e.g. an id attribute, name attribute, href attribute (for a link), etc.).  The one that we're using here is the value” attribute of the input element since this is the attribute that tells us what text has been entered into the input box.  To summarise again, the statement above looks up the input element that goes by the ID txtyourname” in the active HTML document, accesses the text value typed into it ( .value), puts Hello in front, and then shows the resulting text string in an alert box, whenever the user clicks the Hello you” button (see the onclick event attribute of that button).

Finally, let's try adding one more thing to the showHelloYou() function and include an extra test that first checks whether something has actually been entered into the text field.  If so, a hello message is shown as before; otherwise, the user is prompted to enter a name first.   To implement this check, we'll need an if-else” selection statement.  The JavaScript syntax for this statement can be found at:http://www.w3schools.com/js/js_if_else.asp. Have a quick read through the explanation provided there before continuing.

Starting from what you had so far, modify the showHelloYou() function as follows:

function showHelloYou() {

if (document.getElementById("txtyourname").value == "") {

alert("Please enter your name first.")

}

else {

alert("Hello " + document.getElementById("txtyourname").value); }

}

Try the new version out. Does it work as intended?

Activity 3: Adding JavaScript functionality to our online shop page

In this third and final activity for today, you will see another example of JavaScript and how it interfaces with the elements on a HTML page; also, you will learn about declaring and using variables for making calculations.

Make a copy of the HTML document you created in Activity 1, rename it to Activity3.html”, and familiarise yourself again with its markup code. Our goal next is to add some JavaScript functionality that allows the user to check the total price of their order. More specifically, an extra button, labelled “Total cost”, should be included, which may be used to calculate the total cost of the order (i.e., taking into account both order quantities and product prices5).  The result should be shown in a text field next to the former button (see screenshot below).

The first step is to add the extra button and an empty text input element that will later on be used to display the total cost.  Do so based on what you learned earlier.

Secondly, to calculate the correct amount, your script must be able to access the value of the three text input elements in the quantity column of the HTML table (e.g., it will have to figure out that the user entered 5, 1 and 0 in the example given above) and it must be able to write something back to the text input element next to the total cost button.  Recall from the previous activity how to do this by assigning a unique id attribute value to each of these four input elements. Change the HTML code accordingly (leaving the actual script for later).  Make sure that your page is still functioning correctly.  Note that it is good practice to do a quick test after most changes; also it can be very handy to make an occasional backup of your file so that you can always revert to an earlier version if necessary.

Now try to include a JavaScript function that shows the content of each of the three quantity fields in a separate alert box.