javascript and jquery - web technologies (1019888bnr)

41
2 December 2005 Web Technologies JavaScript and jQuery Prof. Beat Signer Department of Computer Science Vrije Universiteit Brussel http://www.beatsigner.com

Upload: beat-signer

Post on 19-Jan-2017

430 views

Category:

Education


0 download

TRANSCRIPT

2 December 2005

Web TechnologiesJavaScript and jQuery

Prof. Beat Signer

Department of Computer Science

Vrije Universiteit Brussel

http://www.beatsigner.com

Beat Signer - Department of Computer Science - [email protected] 2November 4, 2016

JavaScript

High-level loosely typed

dynamic language

Introduced by Netscape in

1995 lightweight interpreted

client-side programming

Supports imperative, object-oriented

and functional programming styles

Nowadays also used in non-web-based environments PDF, Microsoft Office, …

JavaScript implements the ECMAScript specification current version is ECMAScript 2016

[http://stackoverflow.com/research/developer-survey-2016]

Beat Signer - Department of Computer Science - [email protected] 3November 4, 2016

Adding JavaScript to a Webpage

JavaScript code can be placed in the <head>, in the

<body> or in external files

<!DOCTYPE html><html><head><tile>JavaScript Example</tile>...<script>alert("Message in the header");

</script><script src="example.js"></script></head><body><h1>A First Example</h1><script>document.write("<p>Text added by JavaScript</p>");

</script><p id="p2">A second paragraph.</p></body></html>

Beat Signer - Department of Computer Science - [email protected] 4November 4, 2016

Adding JavaScript to a Webpage …

Advantages of external JavaScript files separation of HTML and code

faster page load if JavaScript file is cached

JavaScript code placed just before the </body> tag

(end of the page) might improve page load display of HTML is not blocked by script loading

alternative: attribute defer="true" in the <script> tag

JavaScript errors silently ignored by most browsers activate browser console for debugging (e.g. F12)

Beat Signer - Department of Computer Science - [email protected] 5November 4, 2016

Browser Console

Error 'aalert' shows up in the console

Beat Signer - Department of Computer Science - [email protected] 6November 4, 2016

Output

There are different possibilities for JavaScript output

document.write() adds content to the page while loading

deletes page if used after loading

console.log() outputs content to the browser console

window.alert() or alert() outputs data in an alert message box

innerHTML property adds content to an HTML element (via DOM tree)

document.getElementById("p2").innerHTML = "A new second paragraph.";

Beat Signer - Department of Computer Science - [email protected] 7November 4, 2016

Variables and Data Types

Variables have dynamic types

Good practice to declare a variable before its first use variable that is used without declaring it becomes a global

variable (implied global)

Three primitive data types string, number and boolean

Further there are two special data types null and undefined

var x; // x has been declared but the value is 'undefined'x = "Albert Einstein"; // Now x is a stringx = 3.1415; // Now x is a numbertypeof x; // numberx = false; // Now x is a boolean

Beat Signer - Department of Computer Science - [email protected] 8November 4, 2016

Strings

Any text between single (') or double quotes (")

Strings are immutable

Special characters have to be escaped with with a

backslash (\)

var hello = "Hello World";var correct = "This is \"correct\""; // escaped double quotesvar tmp = hello.length; // 11tmp = hello + ". " + correct; // Hello World. This is "correct"tmp = hello.charAt(1); // etmp = hello.toUpperCase(); // HELLO WORLDtmp = hello.replace("World", "VUB"); // replace first occurence of 'World' with 'VUB'

Beat Signer - Department of Computer Science - [email protected] 9November 4, 2016

Numbers

Only one type of numbers (64-bit floating point) mantissa (52 bits), exponent (11 bits) and sign (1 bit)

NaN indicates that a value is not a number

Infinity for values that are too large to be represented

var x = 42.00;var y = 42;var z = 42e3; // 42000

var x = 42 / "foo"; // but what about 'x = 42 + "foo"?isNaN(x); // returns true// what is the difference between '10 + 10 + "foo"' and '"foo" + 10 + 10'?

var x = 42 / 0; // x becomes Infinity

Beat Signer - Department of Computer Science - [email protected] 10November 4, 2016

Numbers …

Rounding errors due to rounding errors we might not always get the expected

result

var x = 0.3 + 0.6; // 0.8999999999999999var x = (0.3 * 10 + 0.6 * 10) / 10; // possible solution (resulting in 0.9)

Beat Signer - Department of Computer Science - [email protected] 11November 4, 2016

Boolean

Booleans can have the values true or false

var x = true;var y = false;var z = 5 > 3; // true

Beat Signer - Department of Computer Science - [email protected] 12November 4, 2016

Date and Math Objects

Date object can be used to work with dates

Math object can be used for various mathematical

operations and offers some constans (e.g. PI and E)

var now = new Date();var nextWeek = new Date("2016-11-04T14:00:00"); // ISO 8610 syntaxvar milis = now.getTime(); // time in milliseconds since January 1, 1970var test = nextWeek.getTime() > now; // true

Math.random(); // random number between 0 (inclusive) and 1 (exclusive)Math.round(3.6); // 4 (rounded to the nearest integer)Math.max(4,10,3); // 10 (number with the highest value)

Beat Signer - Department of Computer Science - [email protected] 13November 4, 2016

Objects

Container of properties (name/value) where a value can

be any JavaScript value (including other objects)

Two possibilities to retrieve object values second option only works for legal JavaScript names and

non-reserved words

var student = {firstName: "John",lastName: "Harper",height: 182};

student["firstName"];student.lastName;

Beat Signer - Department of Computer Science - [email protected] 14November 4, 2016

Objects ...

Existing values can be updated, new properties can be

added and existing properties can be deleted

Objects are passed by reference and not by value

Cloning of objects (deep copy) is not trivial in JavaScript e.g. jQuery offers a clone() method

student.lastName = "Wayne"; student.address = {street: "Pleinlaan",number: 2};delete student.lastName;

var x = student; // student object created beforex.firstName = "Peter";var name = student.firstName; // name is "Peter" since x and student are references

// to the same object

Beat Signer - Department of Computer Science - [email protected] 15November 4, 2016

Arrays

An array is a variable that can hold multiple values which

can be accessed via an integer offest values of different types might be mixed

Other methods to sort arrays, combine arrays etc.

var points = [10, 5, 17, 42];points.length; // number of elements (4)points[1]; // accesses the element with the given offset (5)points[points.length] = 13; // adds 13 to the end of the array [10, 5, 17, 42, 13]var last = points.pop(); // removes the last element [10, 5 , 17 , 42]var l = points.push(2); // adds 2 at the end and returns the length (5)var first = points.shift(); // removes the first element [5, 17, 42, 2]l = points.unshift(7); // adds 7 to the beginning and returns the length (5)delete points[2]; // the third element will be undefinedvar matrix = [[3, 1, 2], [9, 6, 4], [5, 7, 8]]; // array of arrays ("2D" array)matrix [1][2]; // 4

Beat Signer - Department of Computer Science - [email protected] 16November 4, 2016

Functions

A function is a block of code to perform a particular task enables the reuse of code

functions are objects and can be used like any other value

- can be stored in variables, objects and arrays

- can be passed as argument to functions or returned from functions

access to a function without the () operator returns the definition of a function

function multiply(p1, p2) {return p1 * p2;}

var r = multiply(3, 4); // 12

Beat Signer - Department of Computer Science - [email protected] 17November 4, 2016

Scope

Local variables declared within a function can only

be accessed within the function (function scope) note that there is no block scope

A variable declared outside of a function has global

scope

A value assigned to a non-declared variable

automatically becomes a global variable (implied global)

Local variables deleted when the function is completed

Global variables are deleted when the page is closed

Function arguments (parameters) work as local variables

within functions

Beat Signer - Department of Computer Science - [email protected] 18November 4, 2016

Objects Revisited

Functions can be added to objects (methods)

Multiple objects can be created via an object constructor

function (prototype)

// Let us assume that we have the student object that was created earlierstudent.fullName = function() {return this.firstName + " " + this.lastName;}

function student(firstName, lastName, height) = {this.firstName = firstName;this.lastName = lastName;this.height = height;this.fullName = function() {return this.firstName + " " + this.lastName;}};

var student1 = new student("Audrey", "Sanctorum", 174);var student2 = new student("Lars", "Van Holsbeeke", 177);

Beat Signer - Department of Computer Science - [email protected] 19November 4, 2016

Conditional Statement

Used to perform different actions based on different

conditionsvar mention = "";

if (grade < 10) {mention = "Fail";

} else if (grade < 14.5) {mention = "Pass";

} else {mention = "Distinction";}

Beat Signer - Department of Computer Science - [email protected] 20November 4, 2016

Loops

For Loop

For/In Loop iterate over object properties

While Loop

for (i = 0; i < 10; i++) {text += "Number: " + i + "<br />";

}

for (x in student) {text += " " + student[x]; // Add all properties of 'student' to text string

}

while (i < 10) {text += "Number: " + i + "<br />";i++;

}

Beat Signer - Department of Computer Science - [email protected] 21November 4, 2016

Events

Various events can be triggered when accessing an

HTML document document has finished loading

form field has been changed

button has been clicked

mouse is moved over an image

...

JavaScript can be used to trigger some actions when

events are detected

<button onclick="startSlideshow()">Start</button>

Beat Signer - Department of Computer Science - [email protected] 22November 4, 2016

JavaScript Best Practices

Avoid (minimise) global variables global variables can lead to name collisions for sub-programs

possible to define one global variable acting as container for all the other variables (added as properties)

Always declare variables (var) before they are used otherwise they will become global variables (implied global)

Always initialise variables when they are declared avoids undefined values

Put all declarations at the top of each script or function no block scope and variable visible within the entire function

(function scope)

var MYAPP = {};MYAPP.title = "Hello World App"; // modules in ECMAScript 2016 solve the problem

Beat Signer - Department of Computer Science - [email protected] 23November 4, 2016

JavaScript Best Practices ...

Always use the === and !== equality operators == and != do some automatic type coercion (with complicated

rules) if the types are not equal

Do not use the typed wrappers new Boolean(),

new Number() and new String() also use {} instead of new Object() and [] instead ofnew Array()

Avoid block-less if, while, do or for statements

Avoid the use of eval() runs text as code and leads to performance and security issues

if (x > 10) {t = true;}

Beat Signer - Department of Computer Science - [email protected] 24November 4, 2016

jQuery

JavaScript library that simplifies the

use of JavaScript on websites HTML/DOM traversal and manipuation

event handling

effects and animation

AJAX

Most popular and extendable JavaScript framework large developer community

Two ways to add jQuery to a website download jQuery library (JavaScript file) from jquery.com

link to jQuery library on content delivery network (CDN) server

- Microsoft, Google, …

Beat Signer - Department of Computer Science - [email protected] 25November 4, 2016

jQuery ...

jQuery code executed when document loaded (ready)

<!DOCTYPE html><html><head><tile>jQuery Example</tile>...<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script>$(document).ready(function(){// jQuery code

});</script></head><body>...</body></html>

Beat Signer - Department of Computer Science - [email protected] 26November 4, 2016

DOM Revisited

cross-browser issues when accessing DOM via JavaScript

News

html

head body

document

title

Vrije Univer ...

h1 p p …

aInternation ...

Vrije Uni ...

href

http:// ...

root node

document.getElementsByTagName("h1");document.getElementById("main");

JavaScript

Beat Signer - Department of Computer Science - [email protected] 27November 4, 2016

jQuery Syntax

jQuery syntax makes it easy to select HTML elements

(based on CSS-style selectors) and perform some

actions on these elements $ sign to access jQuery followed by a selector and the action to

be performed on the selected elements

Examples

$(selector).action();

$("h1").hide(); // hide all h1 elements (implicit iteration)$("h1").hide().delay(500).fadeIn(1500); // multiple methods can be chained$("h1:first").hide(); // hides the first h1 element$("#main").hide(); // hides the element with id=main$(".note").toggle(); // toggles all elements of class note$("p:even").toggle(); // toggles all even paragraph elements$("h1").html(); // get content from first h1 element$("h1").each(function() {...}); // loop over each h1 element$("p").html("New"); // updates the content of all p elements to "New"

Beat Signer - Department of Computer Science - [email protected] 28November 4, 2016

Caching jQuery Selections

A jQuery object (result of a selection) has references to

the elements in the DOM tree if the same selection is used multiple times, the jQuery object can

be reused (cached) by storing it in a variable

var $paragraphs = $("p"); // often prefix $ used for variables with a jQuery object

Beat Signer - Department of Computer Science - [email protected] 29November 4, 2016

Attributes

Attributes can be accessed and updated

Similar functionality exists for classes

$("a:first").attr("href"); // get the href attribute of the first anchor tag$("a:first").attr("href", "http://wise.vub.ac.be"); // update attribute$("a:first").removeAttr("href"); // remove href attribute of the first anchor tag

$("p").addClass("main"); // adds an additional class$("p").removeClass("main"); // removes the class main

Beat Signer - Department of Computer Science - [email protected] 30November 4, 2016

Event Handling

Deals with cross-browser issues behind the scenes

There are various jQuery events from different sources keyboard

- input, keydown, keyup, keypress

mouse

- click, dblclick, mouseup, mousedown, mouseover, mousemove, mouseout,

hover

UI

- focus, blur, change

form

- submit, select, change

document

- ready, load, unload

Beat Signer - Department of Computer Science - [email protected] 31November 4, 2016

Event Handling ...

We can handle events via the on() method the first paramter is the event to respond to and the second

parameter is named or anonymous function

$("#start").on("click", startSlideshow();); // calls a named function$("p").on("mouseover", function(e) { // anonymous function$(this).hide();});

Beat Signer - Department of Computer Science - [email protected] 32November 4, 2016

DOM Navigation

Various methods can be used to start navigating the

DOM tree from a given selection parent()

- direct parent of current selection

parents()

- all parents of current selection

children()

- all children of current selection

next ()

- next sibling of current selection

siblings()

- all siblings of current selection

...

Beat Signer - Department of Computer Science - [email protected] 33November 4, 2016

Other JavaScript Libraries

jQuery UI various widgets and effects

jQuery Mobile touch optimised interaction for mobile devices

Modernizr.js check availability of certain features in a browser

D3.js interactive data visualisations

Beat Signer - Department of Computer Science - [email protected] 34November 4, 2016

JavaScript Object Notation (JSON)

Developed as an XML alternative to represent JavaScript

objects as strings (language independent)

Easy to produce and faster to parse than XML supports different data types

JSON is based on a subset of JavaScript JSON document can be read via the JavaScript eval() function

- security issues: note that this approach can be dangerous if the source is not

trusted since any JavaScript code might be executed

most recent browsers offer a JSON parser

- recognises only JSON data types and rejects any scripts

Many Web 2.0 Applications offer a JSON interface Flickr, YouTube, Delicious, ...

Beat Signer - Department of Computer Science - [email protected] 35November 4, 2016

JSON Data Types

The values themselves can be simple values (number,

boolean or string), arrays or objects nesting is supported

Type Description

Number integer, real or float

Boolean true or false

String double-quoted Unicode (use backslash for escaping)

Array comma-separated ordered sequence of values enclosed in

square brackets

Object comma-separated collection of key:value pairs enclosed in

curly brackets

null null value

Beat Signer - Department of Computer Science - [email protected] 36November 4, 2016

JSON Syntax Diagrams

http://www.json.org

Beat Signer - Department of Computer Science - [email protected] 37November 4, 2016

JSON Example

{"surname": "Signer","forename": "Beat","address": {

"street": "Pleinlaan 2","city": "Brussels","postalCode": 1050,"country": "Belgium"

},"phoneNumbers": [

{ "type": "office", "number": "123 456 789" },{ "type": "fax", "number": "987 654 321" }

]}

Beat Signer - Department of Computer Science - [email protected] 38November 4, 2016

Exercise 5

CSS3 get some hands-on experience with CSS3

Beat Signer - Department of Computer Science - [email protected] 39November 4, 2016

References

JavaScript: The Good Parts, Douglas

Crockford, O'Reilly Media (1st edition), May 2008,

ISBN-13: 978-0596517748

JavaScript and JQuery: Interactive Front-End Web

Development, Jon Duckett, Wiley (1st edition),

June 2014, ISBN-13: 978-1118531648

JavaScript Tutorial http://www.w3schools.com/js/

jQuery Tutorial http://www.w3schools.com/jquery/

Beat Signer - Department of Computer Science - [email protected] 40November 4, 2016

References ...

JSLint: The JavaScript Code Quality Tool http://www.jslint.com/

2 December 2005

Next LectureXML and Related Technologies