5 HTML, CSS and JavaScript
5.1 HTML
https://www.w3schools.com/tags/ref_byfunc.asp
Tag | Description |
---|---|
!DOCTYPE | Defines the document type |
html | Defines an HTML document |
head | Contains information for the document |
title | Defines a title |
body | Defines the documents body |
h1 to h6 | Defines headings |
p | Defines a paragraph |
br | Inserts a single break |
hr | Defines a thematic change in the content |
span and div | A div is a block-level element and a span is an inline element. Div should be used to wrap sections of a document, while span to wrap small portions of text, imgages etc. |
HTML is made up of a structure of elements which acts like a set of instructions for a web browser.
<!-- Doctype declares which dialects of HTML that is used. In this case HTML5 -->
<!DOCTYPE HTML>
<!-- <html> is the parent element for the page. All other elements are nested within this. <html> always has two child elements: <head> and <body>. -->
<html>
<!-- <head> element contains information about the web page such as its title, links to other resources etc. Nothing in the this element is visible on the page. -->
<head>
<title> Web Page Test</title>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,300;1,300&display=swap" rel="stylesheet">
</head>
<!-- <body> element takes care of the actual visible content on the page. -->
<body>
<header>
<nav>Home | About | Contact </nav>
<hgroup>
<h1>Web page test</h1>
<h2>Not very complexed</h2>
</hgroup>
</header>
</body>
</html>
5.2 CSS
There are two ways to include CSS in the HTML document. Embedded style sheet is one where all of the selectors and style rules appear in the “head” element of the HTML. With an external style sheet, CSS is written in a separate file and then linked.
<head>
<title> Web Page Test</title>
<link href="https://fonts.googleapis.com/css2?family=Lato:ital,wght@0,300;1,300&display=swap" rel="stylesheet">
<style>
body {
font-family:"Lato";
}
#wrapper {
width: 80%;
height: auto;
margin-left: auto;
margin-right: auto;
}
section {
width: 70%;
height: auto;
float: left;
}
aside {
width: 30%;
float: right;
}
footer {
width: 100%;
height: auto;
float:left;
}
h1 {
font-weight: bold;
font-size: 26px;
color:#990000;
}
hgroup > h1 {
margin-bottom: 3px;
}
#homepageImage {
float:left;
border-style:none;
}
</style>
</head>
5.3 JavaScript
Sublime can be used as a starting IDE.
Link scripts to page. Write the script in a separate file and save with a .js filename. The script is then lnked to a page using the src attribute of the script element.
https://www.fincher.org/tips/Languages/javascript.shtml
5.3.1 Operators
Operator | Description | Example |
---|---|---|
?? | Returns true if both operands evaluate to true | true && false (false) |
|| | Returns true if either operand evaluates to true, otherwise false | if (x == y || y > z) |
! | Inverts the boolean value of the operand | !true (false) |
5.3.2 Keywords
JavaScript defines a set of keywords known as reserved words, these include: break, case, catch, continue, default, delete, do, else, false, finally, for, function, if, in, instanceof, new, null, return, switch, this, throw, true, try, typeof, var, void, while, with.
Keyword | Description | Example |
---|---|---|
var | The “var” keyword tells the browser to create variables. | var x,y; |
this | The “this” keyword refers to the object it belongs to. | fullName : function() { return this.firstName + " " + this.lastName; } |
const | For varibles that don´t change, we use const. | const taxRate = 0.3050 |
5.3.3 Anatomy
All JavaScript instructions are contained within statements. Related statements can be grouped together into a block by wrapping the statement in braces.
5.3.3.1 Conditional statements
//Multiple statements
if(condition) {
statement_1;
statement_2;
statement_3;
}
//Else clause
if(condition) {
statement(s);
} else {
statement(s);
}
//Else if clause. Branching logical structure can get very complex.
if(condition) {
statement(s);
} else if(condition) {
statement(s);
}
//example
var balance = 400;
if(balance < 0.0){
status= "bankrupt";
} else if(balance < 100.0) {
status = "ok";
} else {
status = "rich";
}
document.write("customer is " +status)
//Switch statement
switch(condition) {
case label_1:
statement(s);
break;
case label_2:
statement(s);
break;
default:
statement(s);
break;
}
//switch examplevar flavor = "vanilla";
switch(flavor) {
case "chocolate":
document.write("I like chocolate too.");
break;
case "strawberry":
document.write("Strawberry is for sissies.");
break;
case "vanilla":
document.write("Vanilla is boring.");
//no break statement so control will continue to the statement below
default:
document.write("Ice cream is cool.");
}
5.3.3.2 Loops
//While loops
while(condition) {
statement(s);
}
//example
var total = 1;
while(total < 100) {
document.write(total+",");
total = total * 2;
}
//Do while
do {
statement(s);
} while(condition);
//For loops
for(initialize ; condition ; iteration) {
statement(s);
}
//Go to (should be used carefully)
for(var i=0; i < 2; i++) {
outerloop:
for(var j=0; j < 10; j++) {
if(j > 3) {
break outerloop;
}
document.write(" "+i+j+", ");
}
}
Loop: existing a loop
5.3.4 Functions and classes
5.3.4.1 Named and anonymous functions
Using anonymous functions we use a variable name instead of a function name.
//Named function
function calculateRectArea(rectWidth, rectHeight) {
return(rectWidth * rectheight)
}
//Anonymous function
var calculateRectHypotenuse = function(rectWidth, rectHeight) {
var widthsquared = rectWidth * rectWidth;
var heigthSquared = rectHeight * rectHeight;
return(Math.sqrt(widthSquared + heightSquared));
}
//calling
var myRectArea = calculateRectArea(49, 28);
var myRectHypotenuse = calculateRectHypotenuse(49,28);
Anonymous function
´´´html <!DOCTYPE html><script type="text/javascript">
var anonbutton = document.getElementById("anonbutton");
anonbutton.onclick = function() {
alert("anonymous function called.");
}
</script>
´´´
5.3.4.2 Namespace
Namespaces are notional spaces or contexts in which a set of names can be defined, to avoid name clashed. Two names can be identical as long as they exist in different namespace.
//Creating a namespace in js script. It is a good practise to include your namespace declaration in top of all your scripts. Functions needs to be anonymous.
//First we create an object called com inside the global namespace, and then we create an object called flametreepublishing inside the com project.
// After declaring, but not initializing, we test that each namespace object does not exist before using it.
var com;
if(!com) {
com = {};
}
if (!com.flametreepublishing) {
com.flametreepublishing = {}
}
5.3.4.3 Object-Oriented
While JavaScript is not a true OOP language, it is still used in a OOP style. We write scripts called classes that define properties.
//Example: Define a custom class, then create an instance.
var com;
if(!com) {
com = {};
}
if(!com.flametreepublishing) {
com.flametreepublishing = {};
}
com.flametreepublishing.QuizQuestion = functio(aQustionNum, AQuestionText, aAnswer, aCorrectAnswerIndex){
this.questionNum = aQustionNum;
this.questionText = AQuestionText;
this.answers = aAnswer;
this.correctAnswerIndex = aCorrectAnswerIndex;
//Creating an instance
new com.flametreepublishing.QuizQuestion(
1,
"Approx how far away from the Earth is the Sun?",
["200 miles", "93 000 000 miles", "49 000 000 miles", "150 000 miles"],
1
)
}
5.3.5 Misc
When JavaScript is referenced from a separate file, the use of async makes the page load ahead of the script.
Variables defines outsisde of a function are global variables, which can be accessed from any function. Local variables only live inside a function. If you forgets to preface with var, the variable becomes global.
var imAGlobalVar = 10;
function foo() {
var imALocalVar = 11; //local variable
imAGlobalVar2 = 12; //global variable, not good practice
}
Associating functions with objects
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Quiz</title>
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
}
var narnia = new movie("Narnia", "Andew Adamson");
document.write(narnia.toString());
</script>
</head>
<body>
</body>
</html>
Prototypes. Objects can have prototypes from which they may inherit fields and functions.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Quiz</title>
<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director || "unknown"; //if null assign to "unknown"
this.toString = movieToString; //assign function to this method pointer
}
var officeSpace = new movie("OfficeSpace");
var narnia = new movie("Narnia","Andrew Adamson");
movie.prototype.isComedy = false; //add a field to the movie's prototype
document.write(narnia.toString());
document.write("<br />Narnia a comedy? "+narnia.isComedy);
officeSpace.isComedy = true; //override the default just for this object
document.write("<br />Office Space a comedy? "+officeSpace.isComedy);
</script>
</head>
<body>
</body>
</html>
Error handling
try {
obj = null;
null.to_s();
} catch (e) {
document.write("Exception: "+e);
} finally {
document.write("<br />Bye.");
}
To execute a method repeatedly
function timer(){
setTimeout('myMethod()',2000);
}
var myId;
...
myId = setInterval('myMethod()',2000);
To close a window
Link
5.3.6 Working with HTML Elements
Buttons
<form name="buttonGalore" method="get">
Your Name: <input type="text" name="mytext"/>
<br/>
<input type="submit" value ="GO!" />
<input type = "reset" value ="Clear All"/>
</form>
Onclick
<form name="buttonsGalore" method="get">
<fieldset style="margin: 1em; text-align: center; padding: 1em;">
<legend>Select a Movie</legend>
<input type="button" value="Godfather" onclick="displayMovie(this)" />
<input type="button" value="Bodyguard" onclick="displayMovie(this)" />
<input type="button" value="Remember the Titans" onclick="displayMovie(this)" />
</fieldset>
</form>
Radio button
<script>
function findButton() {
var myForm = document.forms.animalForm;
var i;
for(i=0;i<myForm.marsupial.length; i++) {
if(myForm.marsupial[i].checked) {
break;
}
}
alert("You selected \""+myForm.marsupial[i].value+"\".");
}
</script>
<form name="animalForm">
<input type="radio" name="marsupial" value="kangaroo" />Kangaroo
<br /><input type="radio" name="marsupial" value="Opossum" />Opossum
<br /><input type="radio" name="marsupial" value="Tasmanian Tiger" />Tasmanian Tiger
<br />
<input type="button" name="GO" value="GO" onclick="findButton()" />
</form>
Accessing Elements
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing</title>
<script type="text/javascript" src="js/main2.js"></script>
<form name="teamForm">
<select name="team">
<option selected="selected">Select NBA team to win it</option>
<option>Lakers</option>
<option>Utah</option>
<option>Golden State</option>
<option>Chicago</option>
<option>Charlotte</option>
</select>
<input type="button" name="submitbutton" value="Team"
onclick="showStatus()" />
</form>
</head>
<body>
</body>
</html>
function showStatus() {
var selectWidget = document.forms.teamForm.elements["team"];
var myValue = selectWidget.options[selectWidget.selectedIndex].value;
alert('You picked \"'+ myValue +"\"");
return true;
}
5.3.6.1 Dynamic HTML elements
Creating a grocery store list
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Testing</title>
<!-- Adding new elements to a list -->
<script>
function addItem() {
var myitem = document.getElementById("ItemToAdd").value;
var mylistItems = document.getElementById("mylist");
var newP = document.createElement("li");
var textNode = document.createTextNode(myitem);
newP.appendChild(textNode);
document.getElementById("mylist").appendChild(newP);
return false;
}
</script>
<form onsubmit="return addItem()" action="#">
<span>Grocery Items:</span>
<input type="text" id="ItemToAdd" value="Milk" />
<input type="button" value="Add" onclick="addItem()" />
</form>
<span>Grocery List:</span>
<ol id="mylist"></ol>
</head>
<body>
</body>
</html>
5.3.7 DOM and events of JS
5.3.7.1 DOM programming
Document Object Model programming allows JavaScript to make changes to a page after it has been loaded.
//We've updated substantially the renderQuestion method. Now, rather than
//relying on document.write, which only works when the page is being loaded,
//we're now using DOM programming techniques to create HTML elements
//on-the-fly from within JavaScript.
com.flametreepublishing.QuizQuestion.prototype.renderQuestion = function() {
//First we create a <div> element in which to store the question's
//content. This <div> is created but does not yet exist on the page
var questionDiv = document.createElement("div");
//We'll set an id attribute on the <div> - later, this will help us to
//identify which question a user clicks on. We'll give the id a leading
//'q' because it is bad practice to start an id value with a number.
questionDiv.id = "q" + this.questionNum;
//Now we create an <h2> element for the question's title
var questionHeading = document.createElement("h2");
//An element's innerHtml property allows us to write HTML that will be
//rendered within that element...
questionHeading.innerHTML = "QUESTION " + this.questionNum;
//Now we add the <h2> to the <div>
questionDiv.appendChild(questionHeading);
//Next, we create a <p> to hold the question text itself, and add
//this to the <div> too.
var questionTextPara = document.createElement("p");
questionTextPara.innerHTML = this.questionText;
questionDiv.appendChild(questionTextPara);
//Now we'll loop through the QuizQuestion object's 'answers'
//array, creating a <p> for each and and adding them
//to our <div> element
for(var i = 0; i < this.answers.length; i++) {
var answerPara = document.createElement("p");
answerPara.innerHTML = this.answers[i];
answerPara.id = "a" + i;
questionDiv.appendChild(answerPara);
}
//Finally, we add the <div> to the body of the page
document.body.appendChild(questionDiv);
}
5.3.7.2 Events
Event Handler
W3C event model
//Create a method for handling user 'click' events
com.flametreepublishing.SimpleQuiz.prototype.clickHandler = function(e) {
//The handler will always be passed an objec that contains data
//about the event that triggered the handler. We're using an identifier
//of 'e' for this. With a 'click' event, 'e.target' will always refer to
//the HTML element on which the click event occurred.
//First we'll get the id attribute of the clicked answer
var clickedAnswerId = e.target.id;
//Now we need to extract the answer index, a Number, from the id value,
//which is a string. We do this by extracting the second character of the
//id using the 'substr' method of the String class, and then casting this to
//a number. Notice that we can do this all within one compound expression.
var clickedAnswerIndex = Number(clickedAnswerId.substr(1, 1));
//Next we need to know which question has been answered. Recall that we added
//an id attribute to the <div> that contains the question - this <div> is the
//parent of the answer <p> that was clicked, so we can access it using
//'e.target.parentNode'.
//Once we have a reference to the <div> we can extract the question index in
//much the same way as we did the answer index
var clickedQuestionId = e.target.parentNode.id;
var clickedQuestionNum = Number(clickedQuestionId.substr(1, 1));
//The question number stored in the containg <div> id attribute is one-based, but
//we need a zero-based number when accessing the questions array - for this reason
//we subtract '1' from the clickedQuestionNum when retrieving the QuizQuestion object
var clickedQuestion = com.flametreepublishing.simpleQuiz.questions[clickedQuestionNum -1];
//Now that we have the correct QuizQuestion object we can call its 'checkUserAnswer'
//method to see if the user was correct. Recall that 'checkUserAnswer' returns
//'true' or 'false' - all we need do, then, is call the method as the conditional
//expression of an 'if' statement.
if(clickedQuestion.checkUserAnswer(clickedAnswerIndex)) {
alert("Correct! Well done.");
} else {
alert("No - that's not correct. Try again.");
}
}
Event Listener
//The user will click on the answer they believe to be correct, so let's
//add an event listener to the answer's <p>. Note that we don't include
//parentheses '()' after the handler method reference - if we did then
//the handler would be evaluated when the event listener is added to the
//<p>, and this is definitely NOT what we want!
answerPara.addEventListener("click", com.flametreepublishing.simpleQuiz.clickHandler, false)