mysuccess website designer associate

36
MySuccess Website Designer Associate Version 2.0 Topic 9 – Getting Started with JavaScript

Upload: others

Post on 22-Mar-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

MySuccess Website Designer AssociateVersion 2.0

Topic 9 – Getting Started with JavaScript

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 2

In this Lesson

• Topic 9: Getting Started with JavaScript

• Introduction.

• Basic syntax.

• Event handlers.

Introduction

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 4

Introduction to JavaScript

• JavaScript is the programming language of the web.• Whilst HTML defines the content and CSS the layout, JavaScript defines the

functionality.• JavaScript is a standardised, open language. • In this course, you will learn the most important and useful functions of

JavaScript, but we will not cover the whole language, as that’s a course in itself!

• JavaScript has no relation whatsoever to the Java programming language.

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 5

Introduction to JavaScript• JavaScript code can be placed in the <head> or <body> sections of an HTML

document.• The code must be surrounded by <script> tags.• It is no longer to specify type=“text/javascript” in the tag.• Alternatively, you can place code in a separate file, and link to it from HTML

using <script src=“location”>.• It’s a good idea to place JavaScript code at the bottom of the page body.• This will improve page load time, as script compilation can slow down the

display.

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 6

Introduction to JavaScript• Let’s add some example code to the bottom of <body> in the index page of

our newspage project.</footer>

<script> alert('Hello, World!');

</script>

• Let’s create a section to show page loaded time in the footer, and then populate the content with JavaScript. <footer>

&copy; 2016 ICE Malta | Last Modified: <time datetime="2016-09-12T16:42:32Z">13/09/2016 at 16:42:32</time>

| <span id="pageLoaded"></div></footer>

<script>

document.getElementById("pageLoaded").innerHTML = "Page Loaded: " + Date();</script>

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 7

Introduction to JavaScript• To keep our code tidy, we can move the JavaScript content to a separate file.• Create a file called index.js and add the following content:

• Now replace the script content with a link to the file we created.<script src="index.js"></script>

document.getElementById("pageLoaded").innerHTML = "Page Loaded: " + Date();

• The browser will now load this JavaScript from the specified file, and run it as if it were in the HTML file itself.

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 8

Introduction to JavaScript• The alert() method displays text in a pop up message box.• The innerHTML() method can be used to replace the content of an element

on the page. • We can also use console.log() to output text to the browser console.

console.log("Hello from JavaScript");

• The console can be brought up as follows:• Chrome: View > Developer > JavaScript Console• Firefox: Tools > Web Developer > Web Console• Safari: Develop > Show Error Console• Edge & Internet Explorer: F12• Opera: View > Developer Tools > Opera Dragonfly

Basic Syntax

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 10

Basic Syntax• Values• JavaScript defines two types of values: Literal values and variable values.• Values are either numeric or strings, strings must be enclosed in single

our double quotes.• Variables are created using the var keyword, with the equals sign used to

assign values to variables.//Literal values42 //Literal number"Hello" //Literal string'Hello' //Also literal string

//Variablesvar x = 42; var name = "Joe";

• Comments are created using double forward slashes (//comment) or by using /* comment */

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 11

Basic Syntax• Operators:• = assignment operator, assign values to variables.• + - * / arithmetic operators.• + concatenation operator (when used with non-numeric values)

• Expression• An expression is a combination of values, variables and operators which

computes to a value. var x = 6; //Assigning 6 to xy = x + 20; //Expression y = y + (x * 4) / 2; //Expression

• JavaScript is case sensitive. lastName and lastname are two different variables.

• Similarly, var is interpreted as a keyword, but Var is not.lastname = "Doe";lastName = "Micallef";

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 12

Data Types• JavaScript supports several data types, however it is a loosely typed

language.• This means that you do not specify the data type of a variable when declaring

it. • JavaScript infers the type of data from the value placed in the variable.

var x = 6; //x is a numberx = "Hello"; //x is now a stringx = false; //x is now a booleanx = ["Joe", "Frank", "Kate"]; //x is now an arrayx = {name:"Joe", surname:"Doe"}; //x is now an object

Type DescriptionNumber 64-bit floating point number

String Used for text

Boolean Used for true/false

Arrays Used to hold several data values

Objects Used to hold several named values

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 13

Data Types• The typeof operator can be used to discover the type of a variable.

typeof "John" // Returns "string" typeof 3.14 // Returns "number" typeof false // Returns "boolean" typeof [1,2,3,4] // Returns "object" (not "array", see note below) typeof {name:'John', age:34} // Returns "object"

• JavaScript returns object for arrays, since JavaScript arrays are objects.• Special types include null and undefined, as well as empty variables:

var v1 = ""; console.log(typeof(v1)); //Stringvar v2 = null;console.log(typeof(v2)); //Objectvar v3; console.log(typeof(v3)); //Undefined

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 14

Operators• JavaScript supports increment and decrement operators.

var num = 10;console.log("num: " + num);console.log("++num: " + ++num); console.log("--num: " + --num); console.log("num*=10: " + (num*=10));

• Placing the ++ or -- prior to the variable causes a pre-increment (i.e. first perform the operation, then use the value).

• Placing the ++ or -- after the variable causes a post-increment (i.e. first use the value, then perform the operation).var num = 10;console.log("num: " + num);console.log("num++: " + num++); console.log("num--: " + num--); console.log("num*=10: " + (num*=10));

• Note that num*=10 is the same as num = num * 10.• Also available for the other operators.

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 15

Operator PrecedenceOperator Description Example

() Expression grouping (3 + 4)

.[]

MemberMember

person.nameperson[“name”]

()new

Function callCreate

myFunction()new Date()

++--

Postfix incrementPostfix decrement

i++i--

++--!typeof

Prefix incrementPrefix decrementLogical notType

++i--i!(x==y)typeof

*/&**

MultiplicationDivisionModulo divisionExponentiation

10 * 510 / 510 % 510 ** 2

+-

AdditionSubtraction

10 + 510 - 5

<<>>

Shift leftShift right

x << 2x >> 2

<<=>>=

Less thanLess than or equalGreater thanGreater than or equal

x < yx <= yx > yx >= y

=====!=!--

EqualStrict equalUnequalStrict unequal

x == yx === yx != yx !== y

&&||

AndOr

x && yx || y

Operator Description Example

=+=-=*=/=

AssignmentAssignmentAssignmentAssignmentAssignment

x = yx += yx -= yx *= yx /= y

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 16

Functions• A JavaScript function is a block of code designed to perform a particular task. • A function accepts parameters as input, and returns output.

function add(num1, num2) {return num1+num2;

}

console.log(add(4, 12));

• The block of code of a function starts with the { (opening brace) symbol, and ends with the } (closing brace) symbol.

• Variables declared within a function block (or any block) cannot be accessed outside that block.

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 17

Objects• JavaScript supports object-oriented programming – but not in the way you

might be accustomed to!• Here’s a basic definition:

• Here, we are using the Person object directly. • Note how Person is a prototype, not a class in the traditional

sense.

var Person = {firstName: "",lastName: "", age: 0, getFullName: function() {return this.firstName + " " + this.lastName;

} } Person.firstName = "Joe";Person.lastName = "Doe";console.log(Person.getFullName());

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 18

Multiple Instances• To create a class from which you can create multiple instances, you need to

declare a function prototype. var Person = function() {};

• We can now add constructors, properties (fields) and methods to this class.//Define the class with fields and constructorvar Person = function(firstName, lastName, age) {this.firstName = firstName;this.lastName = lastName;this.age = age;

}; //Add a methodPerson.prototype.getFullName = function() {return this.firstName + " " + this.lastName;

}Person.prototype.getAge = function() {return this.age;

}

var p1 = new Person("Joe", "Doe", 20);var p2 = new Person("Kate", "White", undefined);

console.log(p1.getFullName() + " is " + p1.getAge());console.log(p2.getFullName() + " is " + p2.getAge());

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 19

Multiple Instances• Note that you can add properties on the fly:

p1.favouritePizza = 1;console.log(p1);

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 20

Conditions• A conditional statement in JavaScript is represented by ‘if’. • We can use ‘if’ statements to decide on a course of action to take.

if (p1.getAge() >= 18) { console.log(p1.getFullName() + " can drive");

} else {console.log(p1.getFullName() + " cannot drive");

}

• We can have multiple clauses:if (p1.favouritePizza == 1) {console.log(p1.getFullName() + "'s favourite pizza is Margherita");

} else if (p1.favouritePizza == 2) {console.log(p1.getFullName() + "'s favourite pizza is Funghi");

} else if (p1.favouritePizza == 3) {console.log(p1.getFullName() + "'s favourite pizza is Capricciosa");

} else {console.log(p1.getFullName() + " likes some other pizza");

}

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 21

Conditions• Multiple conditions can be separated by logical operators.• We use && for AND, and || for OR.

p1.nAlevels = 2;

if (p1.age >= 25 || p1.nAlevels >= 2) {console.log(p1.getFullName() + " can apply for university");

} else {console.log(p1.getFullName() + " cannot apply for university");

}

p1.hasLicense = false;

if (p1.age >= 18 && p1.hasLicense) { console.log(p1.getFullName() + " can legally drive");

} else {console.log(p1.getFullName() + " cannot legally drive");

}

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 22

Loops• Loops can be used to repeat an action a number of times.• The for loop can be used to do this:

for (i = 0; i < 10; i++) { console.log('iteration ' + i);

}

• You can also use the while loop.var i = 0; while (i < 10) {console.log('Iteration ' + i);

i++; }

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 23

Loops• The do-while loop is JavaScript’s post-tested loop.

var i = 0; do {console.log('Iteration ' + i);i++;

} while (i < 10);

Event Handling

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 25

Event Handling

• For a full list, see: http://www.w3schools.com/js/js_events.asp

Event Descriptiononchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

• JavaScript code and functions can be attached to events generated from your page.

• For example, you can attach code to run when a button is clicked, when the page is closed, when a user inputs data in a form field and so on.

• The code is attached to HTML events, here are some commonly used events:

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 26

Event Handling

• Many times, the functionality provided by JavaScript and events is used to make changes in the HTML DOM.

• Code can be run when an event is triggered, for example:<h1 onclick="this.innerHTML='Ooops!'">My News Feed</h1>

• You can also call a function.<h1 onclick="changeText(this)">My News Feed</h1>

function changeText(id) {id.innerHTML = "Changed!";

}

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 27

HTML DOM

• By using ‘innerHTML’ in the previous example, we changed the HTMLcontent of an HTML element.

• HTML DOM – Document Object Model.• A standard for how to get, change, add or delete HTML elements.

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 28

HTML Document Object

• Changing elements:

• Within the DOM, the Document objects represents the current page.• Finding elements:

Method Example Descriptiondocument.getElementById(id) document.getElementById(“username”) Find an element by element id

document.getElementsByTagName(name) document.getElementsByTagName(“h1”) Find elements by tag name

document.getElementsByClassName(name) document.getElementsByClassName(“featuredArticle”) Find elements by class name

Method Example Descriptionelement.innerHTML = new content id.innerHTML = “Hello, World!” Change the inner HTML of an element

element.attribute = new valueelement.setAttribute(attribute, value)

img.src=“newImage.png”img.setAttribute(“src”, “newImage.png”)

Change the attribute value of an element

element.style.property = new style img.style.width = ”800px” Change the style of an element

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 29

HTML Document Object

• You can also add even handlers to elements using DOM.

• Adding and deleting elements:Method Descriptiondocument.createElement(element) Create an HTML element

document.removeChild(element) Remove an HTML element

document.appendChild(element) Add an HTML element

document.replaceChild(element) Replace an HTML element

document.write(text) Write into the HTML output stream

document.getElementById("saveButton").onclick = function() {alert('You clicked save');

}

Practical Example

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 31

Handling the Contact Form• Let’s use JavaScript to validate the contact form on the contact us page of

our project.• First, we create a JavaScript file to handle the contact page, and link to it in

the body of the page. &copy; 2016 ICE Malta | Last Modified: <time datetime="2016-09-15T16:42:32Z">15/09/2016 at 16:42:32</time></footer>

<script src="contact.js"></script></body>

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 32

Handling the Contact Form• Since we’re using HTML5, our browser will validate the form too. However,

not all browsers display the validation errors. • Since we’re handling the validation ourselves, let’s temporarily disable

browser form validation.<form name="contactForm" id="contactForm" method="POST" action="contact.php" novalidate>

document.getElementById('contactForm').addEventListener('submit', validateContact, false);

• Now we bind a function to the form’s submit event.

• And we declare the function.function validateContact(e) {e.preventDefault(); //Prevent form submission

}

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 33

Handling the Contact Form• Now, we write the function.

function validateContact(e) {e.preventDefault(); //Prevent form submissionvar valid = true;var errorMessage = "";

if (document.getElementById('firstName').value.length == 0) {errorMessage += "Fist name is empty<br>";valid = false;

} if (document.getElementById('lastName').value.length == 0) {

errorMessage += "Last name is empty<br>";valid = false;

} if (document.getElementById('emailAddress').value.length == 0) {

errorMessage += "E-mail is empty<br>";valid = false;

} else if (!isValidEmail(emailAddress.value)) {errorMessage += "E-mail is invalid<br>";valid = false;

} if (document.getElementById('comments').value.length == 0) {

errorMessage += "Comments are empty<br>";valid = false;

} if (!valid) {

document.getElementById("errorMessages").style.display = "block";document.getElementById("errorMessages").innerHTML = errorMessage;

} else {document.getElementById('contactForm').submit();

} }

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 34

Handling the Contact Form• We also need a helper function to validate the e-mail address.

• We add a div to the bottom of the form to show any error messages.

function isValidEmail(email) {var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email);

}

<br> <input type="submit" value="Send"><div id="errorMessages" class="formError"></div>

</form>

• Finally, let’s style the error box./** Form validation */.formError {display: none;background-color: hsla(0, 100%, 65%, 0.5);max-width: 50%; border-radius: 5px;font-weight: 600;padding: 4px;margin-top: 10px;

}

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 35

Handling the Contact Form• Try it out!

MySuccess Website Designer Associate | Copyright © 2013-2017 ICE Malta | Topic 9 | Slide 36

Questions?