asp.net and derivatives html5 = markup + css + javascript ...index-of.co.uk › lectures ›...

31
ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript APIs JavaScript intro http://en.wikipedia.org/wiki/JavaScript

Upload: others

Post on 30-Jun-2020

9 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

ASP.NET and derivatives

HTML5 =

Markup + CSS + JavaScript APIs

JavaScript introhttp://en.wikipedia.org/wiki/JavaScript

Page 2: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Client vs. Server• HTML is just a markup language and when combined with CSS

capable of producing just about every design you could ever desire• In order to have dynamic web content one need to do some client

side programming to produce a RIA (Rich Internet Application)• Client-based programming means that programs run on the visitor’s

computer, within their web browser– All web browsers support this via JavaScript– Adobe ActionScript is another common technology (Adobe Flash) which

is similar to JavaScript

• Server-side programming means that programs run on the web server. The browser never gets to see the program code, only the resulting HTML– Most common languages for writing server-side programs are PHP,

Perl, Python, Ruby and Java, as well as Microsoft’s proprietary languages ASP, ASP.NET and ASP.NET Web Forms/MWC/Web Pages

• Which one of these paradigms to use?– As always it depends on what we want to achieve...

Page 3: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

ASP.NET Web Forms vs. ASP.NET MVC similarities, both:

• is built on top of the ASP.NET framework– i.e. The System.Web namespace– Leverage .NET framework and its languages

• use IIS and the ASP.NET request pipeline– HTTP handlers, HTTP modules and other

components as the configuration framework etc.– Adobe ActionScript is another common technology

(Adobe Flash) which is similar to JavaScript

• render a response to the user– Usually render HTML using code + markup

Page 4: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

ASP.NET Web Forms vs. ASP.NET MVC differences

ASP.NET Web Pages with Razor syntax provide a fast and lightweight way to combine server code with HTML to create dynamic web content using the latest web standards.

Learn more at: http://www.asp.net/

Page 5: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Razor and TypeScript

• Razor syntax, three basic rules• Just write code and markup – don't think about it• @ indicates code• Standard language keywords– e.g. if/else, foreach, etc.

• TypeScript is an Open Source language for application-scale JavaScript development that compiles to plain JavaScript– http://www.typescriptlang.org/

else{<span>@auction.CurrentPrice.Value.ToString("C")</span>

}<p>Start Time: @auction.StartTime.ToString("g")</p>

Page 6: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

JavaScript• JavaScript was originally developed by Brendan Eich of Netscape

around 1995, currently Mozilla Foundation• JavaScript is formalized in the ECMAScript language standard• JavaScript uses syntax influenced by C and copies many names and

naming conventions from Java - NOT to be confused with the Java programming language!

• JavaScript is mainly used in browsers but also in applications outside Web pages as– PDF documents and desktop widgets, runtimes as node.js etc.

• Major implementations– KJS, Rhino, SpiderMonkey, V8, WebKit, Carakan, Chakra

• JavaScript uses dynamic typing as most scripting languages do– For example, a variable x could be bound to a number, then

later rebound to a string• JavaScript is almost entirely object-based and JavaScript objects are

associative arrays - a collection of (key, value) pairs

Page 7: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

What can a JavaScript (JS) do?• JS is a scripting language with a very simple syntax

– Almost anyone can put small "snippets" of code into their HTML pages

• JS can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element

• JS can be used to validate form data before it is submitted to a server– This saves the server from extra processing

• JS can be used to detect the visitor's browser, and load another page specifically designed for that browser

• JS can be used to store and retrieve information on the visitor's computer

• JS can read and change the content of an HTML element• JS uses the HTML DOM (Document Object Model) to

access the elements of a web page

Page 8: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

What is the HTML DOM?• The HTML DOM (Document Object Model) defines a standard way

for accessing and manipulating HTML documents• One of the most common uses for JavaScript is for navigation and

drop-down menus etc. making it look like desktop applications• The DOM presents a HTML document as a tree-structure

HTML DOM Tree Example

Page 9: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

How does HTML5 work?

Page 10: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

How does HTML

5 work?

Page 11: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

JavaScript locations• JavaScript can be written

in the following places• <body>

– The script generate content when the page is loaded

• <head>– The script generate

content when it is needed or before the page loads

– We write our functions here

– This is also where we point to our external scripts

Page 12: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Simple JavaScript• An alert will pop up and we write the current time in the document• Since the JS code is visible via view source in the browser NEVER

do anything regarding security or authentication in JavaScript!

<!doctype html><html><head><meta charset="utf-8"><title>Hello Time</title>

<script>// runs before page load

alert("Hello World!");</script>

</head>

<body>The current time is:<script>

var d = new Date();if (d.getHours() < 10) {

document.write("0");}document.write(d.getHours());document.write(".");if (d.getMinutes() < 10) {

document.write("0");}document.write(d.getMinutes());document.write(".");if (d.getSeconds() < 10) {

document.write("0");}

document.write(d.getSeconds());</script></body></html>

cont

.

time.html

Page 13: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

JavaScript, DHTML and AJAX• In HTML5 JavaScript is the standard script language• JavaScript is object oriented and can be used with AJAX

(Asynchronous JavaScript and XML) and JSON (JavaScript Object Notation) technologies– JSON is a text-based standard for data exchange (as XML)

• The connection between HTML5 (or XHTML), stylesheets and JavaScript is very strong

• DHTML (Dynamic HTML) = manipulation of the DOM• AJAX = DHTML + XMLHttpRequest object

– AJAX makes it possible to update parts of the web page from a server via some AJAX script (JavaScript) without reloading the whole web page

– The script may only call the visited domain for security reasons

Page 14: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

JavaScript testing/debugging• We preferably write JavaScript in some kind of text-editor

which highligts the syntax as Notepad++ etc.– CodeLobster have help and intellisense support!

• To debug (stepwise execution and variable inspection) our JS code we use the built-in web browsers facilities– Internet Explorer and Edge – F12– Google Chrome, Mozilla Firefox – Ctrl-Shift-I– Add-ons/Extensions – Web developer toolbox, Firebug plugin, etc.

• With debug ON you can examine almost everything in JS!– Firefox and Chrome may have the best plugins for debugging?

Page 15: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

JavaScript rules• In JavaScript, each line of code is considered to end either at

the end of the line or at the semicolon– Best practice is to always end every call with a semicolon!

• Both single ' and double ” quotes can be used to mark strings - as long as the quotes at the start and the end of the string match

• JavaScript code/syntax is case sensitive• Comments in JavaScript is done as in C/C++ or Java/C#• It is best to test JavaScript on a web server since some

browsers may not work correctly if the web page is local– This is related to security concerns

• Actually it *is* impossible for JavaScript to access local files on a computer using < HTML5 with one exception – cookies– Cookies have a name and stores personal information in a

key/name - value format for repeated visits until it expires

Page 16: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

The window object and variables

• The window object is the highest object in the DOM hierarchy (above document in earlier DOM slide)– You do not need to include it when writing your code– window.document.write(”text”); => document.write(”text”);

• Variables usually have a datatype, name and a value– var var_name= var_value;

• Variable rules– Must begin with a letter or underscore (digits may be used

after first character)– Variables names are case sensitive– JavaScript does not warn for variables with same name!!– Variable should have describing names of several reasons

• There are no datatypes in JavaScript• Reviewing the code - both for yourself and others

Page 17: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Aritmetic operators• Javascript use dynamic typing - the JavaScript interpreter

will figure out what type to use as your code is running• Operations and operators are more or less exactly as in

C# or Java• Mathematical as (+, -, *, /, %), + also concatenate strings

– var str = ”my ” + ”name”;

• Stepwise increment/decrement (++/--)– a = a+1; (a += 1)

• Compare and relation– (==, !=), (>, >=, <, <=)– (===, !==) when NOT automatic type conversion will be done

• Logic operations – (&&, ||, !), bitwise operators and so on ...

Page 18: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Variable and function//Variable is a symbolic name for a value.//Variables are declared with the var keyword:var x; // Declare a variable named x.//Values can be assigned to variables with an = signx = 0; // Now the variable x has the value 0x // => 0: A variable evaluates to its value.//JavaScript supports several types of valuesx = 1; // Numbers.x = 0.01; // Just one Number type for integers and reals.x = "hello world"; // Strings of text in quotation marks.x = 'JavaScript'; // Single quote marks also delimit strings.x = true; // Boolean values.x = false; // The other Boolean value.x = null; // Null is a special value that means "no value".x = undefined; // Undefined is like null.

//A function is a named and parametrized block of JavaScript code //that you define once, and can then be invoked over and over again.function plus1(x) { // Define a function named "plus1" with parameter "x" return x+1; // Return a value one larger than the value passed in} // Functions are enclosed in curly bracesplus1(y); // => 4: y is 3, so this invocation returns 3+1

var square = function(x) { // Functions are values and can be assigned to vars return x*x; // Compute the function's value}; // Semicolon marks the end of the assignment.square(plus1(y)); // => 16: invoke two functions in one expression

Page 19: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Dialogs• The alert dialog

– Inform the user – general information, warnings etc.– For development showing variables

• The prompt dialog– Lets the user enter text which can be

returned to a variable– var passwd = window.promt('...');

• The confirm dialog– Returns true or false– var cont = window.confirm('…');

<script>window.alert("Information...");var passwd = prompt("Enter password");var cont = confirm("Continue?");

</script>

Page 20: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

while, for, if, else <!doctype html><html> <head> <meta charset="utf-8"> <title>My First JavaScript</title> </head> <body> <script>

var drink = "beer";var lyrics = "";var cans = 5;for(cans=5; cans > 0; cans--)/*while (cans > 0)*/ {

lyrics = lyrics + cans + " cans of " + drink + " on the wall <br>"; //End the line with a HTML line break.lyrics = lyrics + cans + " cans of " //Do it again+ drink + "<br>";//Add the next verse, again using concatentation.lyrics += "Take one down, pass it around,<br>"; // using += operatorif (cans > 1) {

lyrics += (cans-1) + " cans of " //... add the last line.+ drink + " on the wall <br>";

}else { //otherwise, there are no cans left...

lyrics = lyrics + "No more cans of " //add “No more cans” to the end of lyrics.+ drink + " on the wall <br>";

}//cans--; //Reduce the number of cans left by 1 if we used while

}document.write(lyrics);

</script></body></html>

myfirstjavascript.html

Page 21: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

<noscript> element• Check if the user have JavaScript enabled in his browser

– The <noscript> element can contain all the elements that you can find inside the <body> element of a normal HTML page

– The content inside the <noscript> element will only be displayed if scripts not are supported, or are disabled in the user’s browser

• Getting the screen size<!doctype html><html><head><meta charset="utf-8"><title>Screen Size</title></head><body><noscript>Your browser does not support JavaScript!</noscript><script language="javascript">

var w = window.screen.availWidth;var h = window.screen.availHeight;document.write("Your browser support JavaScript! W: " + w + ", H: " + h);if ((w <= 1024) && (h <= 768))

document.write("<img src=image1.jpg>");else if ((w > 1024) && (h > 768))

document.write("<img src=image2.png>");</script></body></html>

screensize.html

Old style < HTML5

Page 22: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Variable problems• Since the var type handles any datatype problems can occur• If you use a ”variable” that has not been declared with the reserved

keyword ”var” a runtime error occur• Use strict mode to introduce better error-checking of your code

– Since 2013 Chrome, Firefox, IE and Edge support ”strict mode”– http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/

• If you use a non initialized variable it will have the value undefined or NaN

<script>"use strict";num; // error!num = 3; // ok, but avoid!var num0;var num1 = 3;var num2 = 3.14;var passwd = "qwerty";var cont = true;

</script>

<script>var myVar;

function foo1(){return myVar - 2;

}function foo2(){

return myVar + "text";}function foo3(){

return !myVar;}foo1(); // returns NaNfoo2(); // returns undefinedfoo3(); // returns true

</script>

strict.html

Page 23: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Variable scope – strict support• Any variable created without the var keyword is created at the

global scope and is not garbage collected when the function returns (because it doesn’t go out of scope), giving the opportunity for a memory leak!

<script>/* Difference between using var and not using var in JavaScript?If you're in the global scope then there's no difference. If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it) */

// These are both globalsvar foo = 1;bar = 2;function scope(){

var foo = 1; // Localbar = 3; // Globalreturn (function(){ "use strict"; return !this; })(); //a nameless function

}// If you're not doing an assignment then you need to use var:// var x; // Declare xdocument.write(scope());</script>

scope.html

Check if strict mode is supportedreturns true if supported

Page 24: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

http://javascript.about.com/library/blreserved.htm

Page 25: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Reserved words ...• In addition to the reserved words, you'd better avoid the

following identifiers as names of JavaScript variables– These are predefined names of implementation-dependent

JavaScript objects, methods, or properties (and, arguably, some should have been reserved words)

• Examples– Alert, Array, close, radio and so on, around 100 words!

• Similarly, the following names (depending on your target browser) may have special meanings as event handlers, and therefore should not be used for any other purpose

• Examples– onclick, onload, onmouseover and so on...– Around 20 in HTML4, HTML5 adds around 50 more

http://www.javascripter.net/faq/reserved.htm

Page 26: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Global functions - isNaN(), parseInt()

• isNaN(number : Number) : Boolean– Check if the parameter is NaN (Not a Number)– Reterns true if number is NaN otherwise false (it is a number)– Useful when checking user entered data in forms

• parseInt(numString : String [, radix : Number]) : Number– Converts a string into a number with the base radix– Returns the first valid number it finds – If no number is found NaN is returned

alert("isNaN(43): " + isNaN("43"));

parseInt("abc") // Returns NaNparseInt("12abc") // Returns 12

isnan.html

Page 27: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Global functions - parseFloat(), isFinite()

• parseFloat(numString : String) : Number– Returns a floating-point number converted from a string– Reterns true if numString is NaN otherwise false (it is a number)– You can test for NaN using the isNaN method

• isFinite(number : Number) : Boolean– Returns a Boolean value that indicates if a supplied number is

finite – you cannot do division with 0– The isFinite method returns true if number is any value other than

NaN, negative infinity, or positive infinity. In those three cases, it returns false

alert("isFinite(10/0): " + isFinite(10/0));

parseFloat("abc") // Returns NaN.ParseFloat("1.2abc") // Returns 1.2

isnan.html

Page 28: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <title>Movies</title> </head> <body> <h1>Movie Showtimes</h1> <h2 id="movie1" >Plan 9 from Outer Space</h2> <p>Playing at 3:00pm, 7:00pm. <span> Special showing tonight at <em>midnight</em>! </span> </p> <h2 id="movie2">Forbidden Planet</h2> <p>Playing at 5:00pm, 9:00pm.</p> </body></html>

JS and the DOM• Do you still remember the

DOM (Document Object Model)?

• Lets say we have the following web page →

movies.html

Page 29: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

document.getElementById()• oElement = object.getElementById(sIDValue)

– Returns a reference to the first object with the specified value of the ID attribute

– sIDValue is a String that specifies the ID value, case-insensitive.

• If we would like to update the text on one of the movies we could use innerHTML - it will be updated after the page has loaded

• Remeber: You cannot modify the DOM before the page has loaded!

• Other things that can be done is – Add and remove elements to/from the DOM– Get and set other element attributes than text

<script>function init() {

var title = document.getElementById("movie1");title.innerHTML = "Red planet";

}// when the page have fully loaded execute init, note that// we do not specify init() since it would run at once thenwindow.onload = init;

</script>

movies.html

We are in the script!

Page 30: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Event functions or methods

<script>"using strict";function myFunc1() {

var text = document.getElementById('txt').value;

console.log(text);alert(text);

}function myFunc2(text) {

console.log(text);alert(text);

}</script></head><body>

<label>Name</label> <input id="txt" name="name" type="text" size="20" value="text" onmouseover="myFunc1();" />

<br /> <br /><input type="button" value="choose" onclick="myFunc2('input button');" /><br /> <br /><button ondblclick="console.log(alert('button'));">No</button>

</body>

myeventfunc.html

• The JavaScript functions are sometimes called methods• Functions can be called from global events which fire off

according to the HTML standard event attributes• With document.getElementById(<element sId>).value

one can get an objects current value• Examples

Page 31: ASP.NET and derivatives HTML5 = Markup + CSS + JavaScript ...index-of.co.uk › Lectures › IA_07_internet-apps-js-intro.pdf · naming conventions from Java - NOT to be confused

Debug with console.log()• You can use the function console.log() to display text in the JS

console which is less intrusive than alert() or document.write()

myeventfunc.html

console.log()Does not work in CodeLobster!