2 December 2005
Web Technologies
JavaScript and jQuery
Prof. Beat Signer
Department of Computer Science
Vrije Universiteit Brussel
http://www.beatsigner.com
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 5November 4, 2016
Browser Console
 Error 'aalert' shows up in the console
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 string
x = 3.1415; // Now x is a number
typeof x; // number
x = false; // Now x is a boolean
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 quotes
var tmp = hello.length; // 11
tmp = hello + ". " + correct; // Hello World. This is "correct"
tmp = hello.charAt(1); // e
tmp = hello.toUpperCase(); // HELLO WORLD
tmp = hello.replace("World", "VUB"); // replace first occurence of 'World' with 'VUB'
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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.8999999999999999
var x = (0.3 * 10 + 0.6 * 10) / 10; // possible solution (resulting in 0.9)
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 syntax
var milis = now.getTime(); // time in milliseconds since January 1, 1970
var 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 before
x.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 - bsigner@vub.ac.be 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 undefined
var 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 earlier
student.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 - bsigner@vub.ac.be 19November 4, 2016
Conditional Statement
 Used to perform different actions based on different
conditions
var mention = "";
if (grade < 10) {
mention = "Fail";
} else if (grade < 14.5) {
mention = "Pass";
} else {
mention = "Distinction";
}
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 of
new 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 36November 4, 2016
JSON Syntax Diagrams
http://www.json.org
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 38November 4, 2016
Exercise 5
 CSS3
 get some hands-on experience with CSS3
Beat Signer - Department of Computer Science - bsigner@vub.ac.be 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 - bsigner@vub.ac.be 40November 4, 2016
References ...
 JSLint: The JavaScript Code Quality Tool
 http://www.jslint.com/
2 December 2005
Next Lecture
XML and Related Technologies

More Related Content

PPT
JavaScript Functions
PPT
CSS Basics
PPTX
Java Data Types
PPTX
Java script
PDF
JavaScript - Chapter 11 - Events
PPT
Javascript arrays
PDF
JavaScript Programming
JavaScript Functions
CSS Basics
Java Data Types
Java script
JavaScript - Chapter 11 - Events
Javascript arrays
JavaScript Programming

What's hot (20)

PDF
JavaScript - Chapter 6 - Basic Functions
PPTX
Arrays in Java
PPT
RichControl in Asp.net
PDF
10. switch case
PPT
Data types
PPTX
Java swing
PPTX
PPTX
PPTX
Java script
PPTX
Scope rules : local and global variables
PDF
Introduction to HTML5
PPTX
Functions in c++
PDF
PPT
358 33 powerpoint-slides_1-introduction-c_chapter-1
PPTX
Html images syntax
PDF
Javascript basics
PDF
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
PPTX
02 data types in java
JavaScript - Chapter 6 - Basic Functions
Arrays in Java
RichControl in Asp.net
10. switch case
Data types
Java swing
Java script
Scope rules : local and global variables
Introduction to HTML5
Functions in c++
358 33 powerpoint-slides_1-introduction-c_chapter-1
Html images syntax
Javascript basics
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
02 data types in java
Ad

Viewers also liked (7)

PPTX
Life Skills Syllabus Overview
DOCX
Life skills course outline
PPTX
jQuery Presentation
PDF
jQuery in 15 minutes
PPTX
Modern Web Technologies
PPTX
jQuery PPT
PDF
jQuery for beginners
Life Skills Syllabus Overview
Life skills course outline
jQuery Presentation
jQuery in 15 minutes
Modern Web Technologies
jQuery PPT
jQuery for beginners
Ad

Similar to JavaScript and jQuery - Web Technologies (1019888BNR) (20)

PPT
Ajax and JavaScript Bootcamp
PPT
Reversing JavaScript
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
PDF
JavaScript Lessons 2023 V2
PDF
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
PDF
Object-oriented Basics
PDF
Web 2.0 Patterns and Technologies - Lecture 07 - Web Information Systems (401...
PPTX
Modern frontend in react.js
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
PPTX
ECMAScript 2015
PDF
JavaScript Lessons 2023
PDF
JavaScript(Es5) Interview Questions & Answers
PPT
JavaScript OOP
PPTX
Oop2010 Scala Presentation Stal
PDF
What's new in Python 3.11
PPT
JavaScript Basics
PPT
Java 7
PPSX
What's New In C# 7
PDF
The Scala Programming Language
PDF
[FT-7][snowmantw] How to make a new functional language and make the world be...
Ajax and JavaScript Bootcamp
Reversing JavaScript
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
JavaScript Lessons 2023 V2
Scott Anderson [InfluxData] | New & Upcoming Flux Features | InfluxDays 2022
Object-oriented Basics
Web 2.0 Patterns and Technologies - Lecture 07 - Web Information Systems (401...
Modern frontend in react.js
Chapter 2 OOP using C++ (Introduction).pptx
ECMAScript 2015
JavaScript Lessons 2023
JavaScript(Es5) Interview Questions & Answers
JavaScript OOP
Oop2010 Scala Presentation Stal
What's new in Python 3.11
JavaScript Basics
Java 7
What's New In C# 7
The Scala Programming Language
[FT-7][snowmantw] How to make a new functional language and make the world be...

More from Beat Signer (20)

PDF
Use Cases and Course Review - Lecture 8 - Human-Computer Interaction (1023841...
PDF
HCI Research Methods - Lecture 7 - Human-Computer Interaction (1023841ANR)
PDF
Evaluation Methods - Lecture 6 - Human-Computer Interaction (1023841ANR)
PDF
Design Guidelines and Models - Lecture 5 - Human-Computer Interaction (102384...
PDF
Human Perception and Cognition - Lecture 4 - Human-Computer Interaction (1023...
PDF
Requirements Analysis and Prototyping - Lecture 3 - Human-Computer Interactio...
PDF
HCI and Interaction Design - Lecture 2 - Human-Computer Interaction (1023841ANR)
PDF
Introduction - Lecture 1 - Human-Computer Interaction (1023841ANR)
PDF
Indoor Positioning Using the OpenHPS Framework
PDF
Personalised Learning Environments Based on Knowledge Graphs and the Zone of ...
PDF
Cross-Media Technologies and Applications - Future Directions for Personal In...
PDF
Bridging the Gap: Managing and Interacting with Information Across Media Boun...
PDF
Codeschool in a Box: A Low-Barrier Approach to Packaging Programming Curricula
PDF
The RSL Hypermedia Metamodel and Its Application in Cross-Media Solutions
PDF
Case Studies and Course Review - Lecture 12 - Information Visualisation (4019...
PDF
Dashboards - Lecture 11 - Information Visualisation (4019538FNR)
PDF
Interaction - Lecture 10 - Information Visualisation (4019538FNR)
PDF
View Manipulation and Reduction - Lecture 9 - Information Visualisation (4019...
PDF
Visualisation Techniques - Lecture 8 - Information Visualisation (4019538FNR)
PDF
Design Guidelines and Principles - Lecture 7 - Information Visualisation (401...
Use Cases and Course Review - Lecture 8 - Human-Computer Interaction (1023841...
HCI Research Methods - Lecture 7 - Human-Computer Interaction (1023841ANR)
Evaluation Methods - Lecture 6 - Human-Computer Interaction (1023841ANR)
Design Guidelines and Models - Lecture 5 - Human-Computer Interaction (102384...
Human Perception and Cognition - Lecture 4 - Human-Computer Interaction (1023...
Requirements Analysis and Prototyping - Lecture 3 - Human-Computer Interactio...
HCI and Interaction Design - Lecture 2 - Human-Computer Interaction (1023841ANR)
Introduction - Lecture 1 - Human-Computer Interaction (1023841ANR)
Indoor Positioning Using the OpenHPS Framework
Personalised Learning Environments Based on Knowledge Graphs and the Zone of ...
Cross-Media Technologies and Applications - Future Directions for Personal In...
Bridging the Gap: Managing and Interacting with Information Across Media Boun...
Codeschool in a Box: A Low-Barrier Approach to Packaging Programming Curricula
The RSL Hypermedia Metamodel and Its Application in Cross-Media Solutions
Case Studies and Course Review - Lecture 12 - Information Visualisation (4019...
Dashboards - Lecture 11 - Information Visualisation (4019538FNR)
Interaction - Lecture 10 - Information Visualisation (4019538FNR)
View Manipulation and Reduction - Lecture 9 - Information Visualisation (4019...
Visualisation Techniques - Lecture 8 - Information Visualisation (4019538FNR)
Design Guidelines and Principles - Lecture 7 - Information Visualisation (401...

Recently uploaded (20)

PDF
GSA-Past-Papers-2010-2024-2.pdf CSS examination
PDF
The 10 Most Inspiring Education Leaders to Follow in 2025.pdf
PDF
NGÂN HÀNG CÂU HỎI TÁCH CHỌN LỌC THEO CHUYÊN ĐỀ TỪ ĐỀ THI THỬ TN THPT 2025 TIẾ...
PPTX
chapter-1-221011141445-58f8b864sdfghj.pptx
PPTX
UCSP Section A - Human Cultural Variations,Social Differences,social ChangeCo...
PDF
Jana Ojana 2025 Prelims - School Quiz by Pragya - UEMK Quiz Club
PDF
Developing speaking skill_learning_mater.pdf
PDF
2003-theological-education-v39-n1-tai lieu
PDF
3-Elementary-Education-Prototype-Syllabi-Compendium.pdf
PDF
English 2nd semesteNotesh biology biopsy results from the other day and I jus...
PDF
HSE 2022-2023.pdf الصحه والسلامه هندسه نفط
PDF
Jana-Ojana Finals 2025 - School Quiz by Pragya - UEMK Quiz Club
PDF
Teacher's Day Quiz 2025
PPTX
Juvenile delinquency-Crim Research day 3x
PDF
Bacterial Diversity and Evolution Bacterial Taxonomy Lecture (4)_.pdf
PDF
IDA Textbook Grade 10 .pdf download link if 1st link isn't working so hard to...
PDF
BP303T PHARMACEUTICALMICROBIOLOGY UNIT 1
PDF
HSE and their team are going through the hazards of the issues with learning ...
PDF
17649-Learning By Doing_text-tailieu.pdf
PDF
Insight into Romanian Wild-Grown Heracleum sphondylium: Development of a New ...
GSA-Past-Papers-2010-2024-2.pdf CSS examination
The 10 Most Inspiring Education Leaders to Follow in 2025.pdf
NGÂN HÀNG CÂU HỎI TÁCH CHỌN LỌC THEO CHUYÊN ĐỀ TỪ ĐỀ THI THỬ TN THPT 2025 TIẾ...
chapter-1-221011141445-58f8b864sdfghj.pptx
UCSP Section A - Human Cultural Variations,Social Differences,social ChangeCo...
Jana Ojana 2025 Prelims - School Quiz by Pragya - UEMK Quiz Club
Developing speaking skill_learning_mater.pdf
2003-theological-education-v39-n1-tai lieu
3-Elementary-Education-Prototype-Syllabi-Compendium.pdf
English 2nd semesteNotesh biology biopsy results from the other day and I jus...
HSE 2022-2023.pdf الصحه والسلامه هندسه نفط
Jana-Ojana Finals 2025 - School Quiz by Pragya - UEMK Quiz Club
Teacher's Day Quiz 2025
Juvenile delinquency-Crim Research day 3x
Bacterial Diversity and Evolution Bacterial Taxonomy Lecture (4)_.pdf
IDA Textbook Grade 10 .pdf download link if 1st link isn't working so hard to...
BP303T PHARMACEUTICALMICROBIOLOGY UNIT 1
HSE and their team are going through the hazards of the issues with learning ...
17649-Learning By Doing_text-tailieu.pdf
Insight into Romanian Wild-Grown Heracleum sphondylium: Development of a New ...

JavaScript and jQuery - Web Technologies (1019888BNR)

  • 1. 2 December 2005 Web Technologies JavaScript and jQuery Prof. Beat Signer Department of Computer Science Vrije Universiteit Brussel http://www.beatsigner.com
  • 2. 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]
  • 3. 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>
  • 4. 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)
  • 5. Beat Signer - Department of Computer Science - [email protected] 5November 4, 2016 Browser Console  Error 'aalert' shows up in the console
  • 6. 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.";
  • 7. 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 string x = 3.1415; // Now x is a number typeof x; // number x = false; // Now x is a boolean
  • 8. 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 quotes var tmp = hello.length; // 11 tmp = hello + ". " + correct; // Hello World. This is "correct" tmp = hello.charAt(1); // e tmp = hello.toUpperCase(); // HELLO WORLD tmp = hello.replace("World", "VUB"); // replace first occurence of 'World' with 'VUB'
  • 9. 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
  • 10. 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.8999999999999999 var x = (0.3 * 10 + 0.6 * 10) / 10; // possible solution (resulting in 0.9)
  • 11. 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
  • 12. 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 syntax var milis = now.getTime(); // time in milliseconds since January 1, 1970 var 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)
  • 13. 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;
  • 14. 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 before x.firstName = "Peter"; var name = student.firstName; // name is "Peter" since x and student are references // to the same object
  • 15. 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 undefined var matrix = [[3, 1, 2], [9, 6, 4], [5, 7, 8]]; // array of arrays ("2D" array) matrix [1][2]; // 4
  • 16. 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
  • 17. 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
  • 18. 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 earlier student.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);
  • 19. Beat Signer - Department of Computer Science - [email protected] 19November 4, 2016 Conditional Statement  Used to perform different actions based on different conditions var mention = ""; if (grade < 10) { mention = "Fail"; } else if (grade < 14.5) { mention = "Pass"; } else { mention = "Distinction"; }
  • 20. 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++; }
  • 21. 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>
  • 22. 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
  • 23. 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 of new 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; }
  • 24. 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, …
  • 25. 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>
  • 26. 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
  • 27. 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"
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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(); });
  • 32. 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  ...
  • 33. 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
  • 34. 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, ...
  • 35. 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
  • 36. Beat Signer - Department of Computer Science - [email protected] 36November 4, 2016 JSON Syntax Diagrams http://www.json.org
  • 37. 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" } ] }
  • 38. Beat Signer - Department of Computer Science - [email protected] 38November 4, 2016 Exercise 5  CSS3  get some hands-on experience with CSS3
  • 39. 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/
  • 40. Beat Signer - Department of Computer Science - [email protected] 40November 4, 2016 References ...  JSLint: The JavaScript Code Quality Tool  http://www.jslint.com/
  • 41. 2 December 2005 Next Lecture XML and Related Technologies