490 likes | 505 Views
This introduction provides an overview of the basic technologies of web programming, including HTML, CSS, and DHTML. It also discusses server-side and client-side programs, with a focus on Javascript and its features, uses, limitations, and basics.
E N D
Intro to Javascript Dr. Joseph M Kuitche Information Technology ASU Polytechnic School
Introduction • Basic technologies of Web Programming: • HTML: Static contents of web pages • CSS: to have consistent look and feel • DHTML: to make dynamic web pages using scripting languages like Javascript, vbscript, etc. • 2 kinds of programs written on the Web • Server-side programs: • Perform various tasks on the server • There should be continuous connection with web server to run server-side scripts • Only developers can create/update/delete the script • As the users are always connected, the server is loaded substantially and the network traffic is also increased • Client-side programs • Solve many of the server-side scripts issues, such as network traffic • Can be tested locally without uploading to a web server • They are likely to be more responsive • But can’t all replace server-side script: can’t do tasks like user auth.
About Javascript • Premier Client-side scripting language used today on the web • Commonly used in tasks from common form data validation to creation of complex user interfaces • Also used to manipulate the markup in the document in which it is contained (Integration with HTML, CSS, XML) • It is becoming first class client-side technology along with HTML, CSS, and XML
Why Javascript? • Has many features like: • Interpreted language • Dynamic web development • Platform independent • Many latest technologies have Javascript as backbone: • AJAX • Flask • Google Chrome Extensions • Mobile Games • MS Gadgets
Javascript Facts • Interpreted language developed by Netscape in September 1995 • Main uses: • Automatically change formatting of a web page • Add contents to a web page • Open new windows containing some data • etc. • Code named: LiveScript • Got changed to JavaScript as Java was becoming popular • Not related to Java: Java & JS are rooted in C lang. • Not meant for writing large programs, but to add functionalities in HTML forms • Platform independent
Javascript Limitations • Some actions cannot be performed using Javascript: • Manipulating browser settings: main windows appearance features, invoking printer, executing codes written for action buttons, etc. • Launching any application on client machine • Reading and writing files on the client and server machines • Sending secret emails • Capturing live data streams from server
JavaScript Basics • JavaScript code is interpreted line-by-line • Variable and function declarations should be put in the document head (head tags) • JavaScript code is case sensitive • Predefined methods, properties, events are case sensitive • e.g. document has bgColor property; but if we write BgColor, it would return “undefined” value • HTML tags are not case sensitive • e.g. “onClick” is the same as “Onclick” • White spaces between the words and tabs are ignored • All statements must end with semi-colon (;) as delimiters • x = x+1; y=y+1; • Scope of the code is given in curly braces: {} • e.g. function f1() { //some statements; }
Data Types • var keyword is used to declare variables • Example: varmyVariable; • JavaScript supports dynamic typing: • The contents or expression assigned to variable decides the data type of the variable • String data type: varsData = “Welcome”; • Numeric data type: varnData = 3.1; • Boolean data type: varbData = true;
Using JavaScript in a browser • JavaScript is included within Script tags • Example: <script type=“text/javascript”> document.write(“<h1>Hello World!</h1>”); </script> • Note • The type attribute allows us to use other scripting languages; the default is Javascript • The simple script above does the same thing as just putting <h1>Hello World!</h1> in the same place in the HTML document • The semi-colon is optional
Dealing with old browsers • Some old browsers do not recognize the script tags • These browsers ignore the script tags, but will display the included JavaScript code • To get them ignore the whole thing: <script type=“text/javascript”> <!-- HTML comments document.write(“Hello World!”); // --> JavaScript comments </script>
3 ways to add JavaScript to HTML • Inline with HTML tags <body onload = “document.bgColor=‘pink’”> Welcome </body> • Internally: Javascript can go in <head> or in <body> • JavaScript functions should be defined in the <head>: This ensures that the function is loaded before it is needed • JavaScript in the <body> will be executed as the page loads • Externally: JavaScript can be written in a .jsfile • <script src=“myJavascript.js”></script> • Put this HTML wherever you would put the actual JS code • The external .js file cannot itself contain the script tags • A .js file lets you use the same code on multiple pages
Demo • script2.html <html> <head> <script type=“text/javascript” src=“myJavascript.js”> </script> </head> </body> <div id=“div1” onClick=“f1()”> click here to show the JavaScript output</div> </body> </html> • myJavascript.js function f1() { document.write(“Welcome!”); }
Functions • Used to encapsulate code that performs a specific task • Sometime we need to have same functionalities again and again • Instead of writing the same code all over again, we can create function and call it repetitively • This leads to code reusability and manageability • Syntax: defined with the keyword function • Functions without parameters function function_name() { statements; } • Functions with parameters function function_name(parameter_list) { statements; } • Calling a function function_name(values);
Demo • demofunction1.html <html> <head> <script type=“text/javascript” src=“myJavascript.js”> var name = window.prompt(“Enter your name: “); sayHello(name); function sayHello(name) { alert(“Hello ” + name); } </script> </head>
Functions with return value • If you need data to be returned from a function, use the return keyword function addition(a, b, c) { return a + b + c; } • Calling function with returned value var res = addition(2, 3, 4) alert(res);
In-class Exercise 1 • Create a website to display the following directions with kilometers instead of miles for our non-US friends From the highway turn right Go 2.4 miles, turn left Go 1.3 miles, turn right Go 1.9 miles, you’re there. • Your program must create a function to convert miles to km (i.e. take miles as parameter and return the corresponding km value). Note that 1 mile is 1.6 km. • Write your Javascript code in an external file. You can use the myJavascript.js created last time.
In-class exercise Solution • demofunction2.html <html> <head> <script type=“text/javascript”> function tokm(miles) { var km = miles * 1.6; return km; } </script> </head> <body> <h1>User-Defined function</h1> <script type=“text/javascript”> document.write(“<b>Directions:</b><br/>”); document.write(“From the highway turn right, <br/>”); document.write(“Go ” + tokm(2.4) + “ km, turn left <br />”); document.write(“Go ” + tokm(1.3) + “ km, turn right <br />”); document.write(“Go ” + tokm(1.9) + “ km, you’re there. <br/>”); </script> </body> </html>
In-class Exercise 2 • Create a website to display a message inputted by the user. If nothing is inputted, display “No user input…” • Your program must create a function to prompt the user for a message and return either the message or the “No user input …” message • Write your Javascript code in an external file. You can use the myJavascript.js created last time. • Javascript Syntax for user input: <variable name> = prompt(msgstr, default); default is the default value for the textfield msgstr is the prompt message
Event Handling • Events occur in response to some user action. • e.gclick on a Button, changing the selected item in a Select • After an occurrence of the event, it’s properties are set & then it is delegated to the target. • Target can be a Java Script function • e.g<input type=“button” onClick=“validate()”> • We can also assign our own function to java script event • myForm.myButton.onclick= isNumber • this will invoke isNumber function when user clicks on myButton.
Type of Events • Keyboard Related events • onKeyPress, onKeyUp • Mouse Click events • onMouseDown, onMouseUp • Drag Drop events • onDragDrop • Window Modification events • onMove, onResize • List of events for window object • onBlur, onFocus, • onLoad, onUnload, • onMove,OnResize, onDragDrop
Event Objects in Javascript • Event object in Java script captures the user events • It packages all properties & methods to manipulate the event attributes • Some important properties • modifiers, pageX, pageY,target, type • Accesing properties • eventObject.property • example code below prints the type of event • <input type="button" name="myButton" value="click" onKeyPress="myFun(event)"> • on key press, myFun() will be called • function myFun(evt) { // print the type of the event alert("Event type "+evt.type); } • Output -> Event Type keypress
Associating Events with functions • Most of the communication from user action to Java script happens through events • We can associate particular event with a Java script function, which does some custom processing on the occurrence of the event • We can also pass some parameters to that method • We can also call more than one function at the happening of the event as shown below • <input type=“button” onClick=“checkLogin();checkPwd() > • here on click of button first checkLogin will be called followed by checkPwd.
Control Structure and Loops • Same structure as C/Java • Conditional: if - else, switch - case • Iteration: while, do … while, for, for … in • Control Statements: Break, Continue • Operators • Arithmetic: + - * / % ++ • Comparison: < <= == != >= • Logical: && || ! • Bitwise: & | ^ ~ << >> >>> • Assignment: += == *= /= %= /= … • String Concatenation: + • Conditional operator: condition?valueIfTrue:valueIfFalse • Special equality tests: • == and != convert operands to same type before the test • === and !== consider their operands unidentical if of different types
IF/Else Demo • script3.html <html> <head> <script type=“text/javascript” src=“myJavascript.js”> </script> </head> </body> <h1 onmouseover=“ifelse()”> If/Else Examples</h1> </body> </html> • myJavascript.js function ifelse() { var state=“CA”, a; //if the variable “a” not 5, write True, else write False // Since no variable “a” is declared, expect False if (a != 5) { document.write(“True <br/>”); } else { document.write(“False <br />”);} if (state==“WA”) document.write(“Pacific Northwest <br />”); else document.write(“Somewhere Else <br />”); }
While Demo • script3.html <html> <head> <script type=“text/javascript” src=“myJavascript.js”> </script> </head> </body> <h1>Control Structure Examples</h1> <ul><li onmouseover=“ifelse()”> If/Else Example</li> <li onClick=“whiledowhile()”> While and Do-While Examples</li></ul> </body> </html> • myJavascript.js function whiledowhile() { vari=1, j=10; while (i <= 10) { document.write(“Guess how many times this while loop will repeat? <br/>”); i += 1; } do { document.write(“Guess how many times this Do-While loop repeats? <br />”); j += 1; } while (j < 11); }
For Demo • script3.html <html> <head> <script type=“text/javascript” src=“myJavascript.js”> </script> </head> </body> <h1>Control Structure Examples</h1> <ul><li onmouseover=“ifelse()”> If/Else Example</li> <li onClick=“whiledowhile()”> While and Do-While Example</li> <li onClick=“forloop()”> For Example</li></ul> </body> </html> • myJavascript.js function forloop() { for (i=1; i <= 10; i++) { document.write(“I bet you know how many times this will repeat <br/>”); i += 1; } }
switch Demo • script4.html <html> <head> <script type=“text/javascript” src=“myJavascript.js”</script> </head> </body> <h1> Switch Example</h1> <p><b>The Computer Wizard!</b></p> <p ondblclick=“switchStatement()”> Ask a Yes/No question and double-click here. </p> </body> </html> • myJavascript.js function switchStatement() { varrandNum = Math.ceil(6*Math.random()); switch (randNum) { case 1: document.write(“Definitely Yes!”); break; case 2 : document.write(“Probably Yes!”); break; case 3 : document.write(“Definitely Maybe!”); break; case 4: document.write(“Probably No!”); break; case 5: document.write(“Definitely No!”); break; default : document.write(“Computer Malfunction, Try Again!”); } }
In-class Exercise 3 • Create a page that checks user input. The user will be prompted for a quantity and must enter a quantity greater than 0. We will assume that the user will enter a number. If the user enters a value of 0 or a negative number, there will be an error message displayed. If the user enters a value greater than 0, a message will be displayed thanking the user for the order. • You need to use a prompt and write messages to the document.. • Write your Javascript code in an external file. You can add your quantity function to the myJavascript.js created last time. • You need to use an input element, with button type. The user will be prompted on click. • Try modifying your code so that instead of displaying an error message, the user is prompted again and again until a value greater than 0 is entered.
Objects in Javascript • Functions are used to provide a uniform method for organizing code. • Objects serve the same purpose for data. • Data items like simple variables are type-less quantities can only hold a single value of some sort at a time. • Objects provide the ability to hold multiple values, so that a group of related data elements could be associated with one another. • Two aspects to JavaScript objects • Creating them • Using them. • What JavaScript calls an object is called a data structure (or class) in many other languages.
Objects in Javascript - 2 • A JavaScript capable browser will provide a number of built–in objects. • Object-oriented programming is a style of programming in which related concepts are grouped together. • If you have five data elements and three functions that manipulate those elements, then you group those elements and functions together into a generic container known as an object. • This is the common ground shared by (almost) all object-oriented programming languages. • Differences arise in the details of how such containers are organized, and in how their contents can be accessed and modified. • It is useful to keep functions that manipulate data items in a specific way with those data items themselves.
Objects in Javascript - 3 • These functions are known as the methods of an object. • Objects collect related data items in a single place and make it simpler to access those items. • JavaScript refers to the items collected within an object as its properties. • JavaScript objects not only store data, they also store functions.
Objects in Javascript - 4 • Javascript is object based language • Almost everything, except loops and relational operators, is defined in the form of object Example: string, document, window, etc. • Objects are used explicitly or implicitly • There are 4 groups of objects: • User-defined objects: Custom objects created by the programmer to have consistency in the tasks assigned • Built-in objects: Objects provided by Javascript itself. These objects are associated with data types such as String, Number, Date. • Browser objects: Not specified as part of the Javascript language, but commonly supported by most of the browsers. Example: window, navigator • Document: Part of DOM • Present programmer with an interface to HTML and XML documents • Also used for manipulating properties of CSS/HTML elements
Basics of Objects • Objects in JS can be created using new keyword Example: var city = new String(); • Objects get deleted and garbage collected automatically once the scope of the object is over • Objects have data that can be accessed by their properties eg: var city = new String(“New York”); alert(city.length); • Constructors are special functions that prepare new instance of an object for use • There are common methods that can be used to perform conversion operations • toString() – converts to string from any object • valueOf() – converts object into an appropriate primitive type, usually a number
Object Demo • customObject.html <html> <head> <script type=“text/javascript”> function Car() { this.isSports = false; } var c1 = new Car(); vartypecar = c1.isSports; if (typecar) document.write(“type of the car is Sports “); else document.write(“type of the car is not Sports ”); </script> </head>
for...in construct • The for...in construct • Used to check whether they have properties or not. • One iteration is used for each property • The loop is not executed if the object doesn’t have any properties. • Syntax for(varname in objname) { …... } • The for…in loop works for customized JavaScript objects also. • This form of the for statement also permits the varname to contain a var declaration.
for...in construct Example • The for...in construct Example • To display all the properties of the Document Object. <HTML> <HEAD><TITLE>EXAMPLE OF THE FOR…IN LOOP</TITLE> </HEAD> <BODY> <PRE> <SCRIPT LANGUAGE = “JAVASCRIPT”> varanobj=document for(varpropname in anobj) { document.writeln(propname) } </SCRIPT></PRE> </BODY> </HTML>
With statement • With statement • Used to avoid repeatedly specifying the object prefix when accessing • properties or methods of an object. • Syntax with(objname) { ……... } • Reference to properties of objname inside the with block occurs as if they had been prefixed with objname and the dot operator (.).
With statement Example • To illustrate the writeln(), write() and alert() methods and the title property of document object using the with statement. <HTML> <HEAD> <TITLE>EXAMPLE FOR WITH STATEMENT</TITLE> <PRE> <SCRIPT LANGUAGE = “JAVASCRIPT”> with (document) { writeln(“1.Testing the ‘with’ statement”) write(“2.Testing the ‘with’ statement”) writeln(“3.Testing the ‘with’ statement”) title= “This is document TITLE” alert(“This is alert”) } </SCRIPT> </PRE> </HEAD></HTML>
Array Objects • Arrays are composite types that store ordered list of data • Arrays are declared using Array() constructor • Empty Array: var arr1 = new Array(); • Array with 2 elements: var arr2 = new Array(“red”, “blue”); • Array with length 5: vararr = new Array(5); • Accessing Array: use the zero-based array index • eg vararr = [10, 20, 30]; • var x = arr[0]; will store 10 in x • Adding, changing, deleting array elements • Add any value at location 2: arr[1] = 75; • Update value at location 2: arr[1] = 50; • To delete an array element, use keyword delete: • deletearr[1]; will delete the value from index 1, i.e. now the second position of the array will be empty
Array Objects - 2 • Length property provides the length or size of the array • It retrieves the index of the next available, i.e. unfilled position at the end of the array • varmyArray = new Array(); • myArray[1000] = “This is the only element in the array”; • alert(myArray.length); will display 1001 • Array Demo: Create an html file called arraydemo.html • Create an array of 4 integers with elements 10, 20, 30, 40 • Display the message “Array Demo” • Display the length and each element on its own line Sample Output Array Demo Array length is 4 Array elements: 10 20 30 40
Array Demo • arraydemo.html <html> <head> <script type=“text/javascript”> vararr = [10, 20, 30, 40]; varlen = arr.length; document.write(“Array Demo <br />”); document.write(“Array length is: ” + len + “<br />”); document.write(“Array Elements: <br/>”); for(vari in arr) document.write(arr[i] + “<br />”); </script> </head>
Date Object • Date is one of the most commonly used javascript objects • Provides methods for manipulating dates and times in html • Stores date and time of client’s machine, usually in ms • Days of the week and months of the year are enumerated beginning with zero • But days of the month are numbered starting with 1 • To create a date, use Date() constructor • This constructor takes many arguments • eg: var d = new Date(); returns the current date and time • Date(milliSeconds): egvar d = new Date(2344556666); • Date(yy,mm,dd); egvar d = new Date(1990, 02, 24); • Date(dateString): egvar d = new Date(“Mar 20, 1990”);
Date Object - 2 • Date object has methods to get/set all the components like year,month,day • getDate() --> Returns date object: egvar d = t.getDate(); • getDay() -->Returns day within week(0-6) • getHours()-->Returns hour within day(0-23) • getMonth()-->Returns month (0-11) • getFullYear()-->Returns the full year • setMonth(value)-->sets the month (0-11) • setHours(value)-->sets the hour (0-23)
Global Objects • There are some methods commonly used in Javascript, but which are not part of any object. • They are said to be part of Global objects • Eval() --> Takes a string and execute as Javascript code • var x = “549”; var y = eval(x); • isNaN() -->Returns a Boolean: true if not a number • var x = isNaN(’54’) -> false; var y = isNaN(NaN) -> true • parseFloat()-->Returns floating point number from string • var x = parseFloat(“33.24”); • parseInt()-->Returns the integer value from string • var x = parseInt(“33.24”); -> 33
Math Objects • Math object of Java Script has functions for all the mathematical operations. • Math.abs(arg): var x = Math.abs(12.3); --> 12 • Math.ceil(arg): var x = Math.ceil(12.3); --> 13 • Math.floor(arg): var x = Math.floor(12.3); --> 12 • Math.max(n1, n2): var x = Math.max(12, 34); --> 34 • Math.min(n1, n2) • Math.sqrt(arg): var x = Math.sqrt(16); --> 4 • Math.pow(x, n): vary = Math.pow(2, 4); --> 16 • Others • Math.round(), Math.random() • Math.exp() • Math.cos(), Math.acos(), Math.sin(), Math.asin(), Math.atan()
String Object • String represents a series of characters • String object in Java Script has many string utility functions • s1 = “hello” // creates a string literal • s1 = new String(“hello”); // creates a string object • Length property returns the length of the string: str.length • Some useful methods • s1 = new String(“team”) • s2 = new String(“workforce”) • s1.charAt(2) --> “a” • s1.indexOf(“m”) --> 3 • s2.lastIndexOf(“o”) --> 5 • s1.concat(s2) --> “teamworkforce” • s1.toUpperCase()--> TEAM • s2.substring(4) -->force
String Object - 2 • String appearance methods are used to control how a string appears when displayed on a web page. • s1.blink() • s1.big() • s1.small() • s1.fontcolor(“color”) • s1.fontsize(“size”) • s1.bold() • s1.italics() • s1.strike() • s1.sub() • s1.sup() • s1.anchor(“anchorString”) • s1.link(“linkString”)