300 likes | 401 Views
ECT 270 Client-side web application development. Introduction to JavaScript. What is Java Script?. JavaScript is not an all-purpose programming language What is JavaScript? JavaScript is NOT Java
E N D
ECT 270 Client-side web application development Introduction to JavaScript
What is Java Script? • JavaScript is not an all-purpose programming languageWhat is JavaScript?JavaScript is NOT Java • JavaScript is an interpreted web scripting language run from the Web browser ( as opposed to CGI scripting that runs on the server side)
JavaScript as DHTML • JavaScript is part of a growing number of HTML extensions known as Dynamic HTML (DHTML). DHTML is comprised of • CSS (cascading style sheets) • DOM (document object module) • Scripting (Javascript and VBscript) • Together, these technologies make the Web what it is today, by enabling far more advanced interactivity and much flashier styling than would HTML on it’s own
Background of JavaScript • Originally created by a team at Netscape and Sun as a subset of Java, with some differences: • Doesn’t need to be compiled, the browser has an interpreter that process the commands in a script • JavaScript commands can be embedded directly into an HTML file (not in a separate applet) • You don’t need to know Object Oriented Programming to use it.
Current version of JavaScript • The European Computer Manufacturers Association (ECMA) is now in charge of the development of a JavaScript standard. • The current version of JavaScript is called ECMA-262 and is supported by most browsers. • Another client-side scripting language supported by Internet Explorer is VBScript
Debugging JavaScript • Syntactic errors: In IE • Internet Options/Advanced • Check box:”Display a notification about every script error” • Check the line indicated and the ones above and below • In Notepad: Edit/Goto enter the line number • If you have syntactic errors the script will not run
Debugging JavaScript • Semantic errors:the syntax is correct but will produce the wrong result • Calculate the average of two numbers • Correct: z = (x+y)/2; • Incorrect: a = x+y/2; • If x=10 and y=30 • z=20 • a=25
JavaScript and HTML • You can place the JavaScript commands in a separate file • Then link the HTML file to that file by using the <SCRIPT> tag in the head of the file <SCRIPT SRC=URL LANGUAGE=“javascript”> other script commands and comments</SCRIPT> • SCRIPT is the tag, LANGUAGE is the attribute, javascript is the value
<!- - Hide this script from browsers that don’t support JavaScript // Stop hiding from other browsers - -> JavaScript and HTML • You can place the JavaScript commands directly in the HTML file • The <SCRIPT> tag can go in the <HEAD> or the <BODY> <SCRIPT LANGUAGE=“JavaScript”> script commands and comments</SCRIPT>
Keep in mind … • JavaScript is case sensitive (commands, objects, methods, function names etc ..) • Each JavaScript command line must end with a semi-colon (;) • One-line comment: // comment • Multi-line comment: /* comment */
<pre> </pre> 07_JSOutput.htm Sending output to the Web page • document.writeln(“string”); • positions output cursor on next line when finished • document.write(“string”); • Leaves the output cursor where it is when done executing • The string can contain any text or HTML source code document is the object, write is the method
JavaScript Variables • A variable is a named element in a program, used to store and retrieve information • Variable names are case sensitive, cannot contain spaces, and must start with a letteror an underscore • When you have more than one word in a variable name, start with a lowercase first letter and capitalize the first letter of any subsequent word: currentDate
Declaring a JavaScript variable • var variableName;(indicates that variableName is a program variable, it doesn’t occupy any space) • var variableName = value; • variableName = value;(also assign an initial value to the variable) • You do NOT need to declare the variable type
07_JSVar.htm Different types of variables • Numeric: 13, 22.3,-3.1415, 5.1E2 (5.1x102) • String: any group of characters within quotation marks. “This is a string”, ‘another string’, ‘3.14’, “” (the empty string) • Boolean: can only be true or falsevarisBad = true; • Null variable: is a variable that has no value (assigned yet)varnoGivenValue;
The Date object • JavaScript doesn’t have a Date data type. You need to create a date object that contains date information. dateVariable = newDate(“month, day, year, hours:minutes:seconds”); ordateVariable = newDate(year, month, day, hours,minutes,seconds); taxDay = new Date (“April, 15,2003,24:0:0”);or = new Date (2003,3,15,); today = new Date ();
Dates in JavaScript • Seconds and minutes: 0-59 • Hours:0-23 • Week Days:0 (Sunday) – 6 (Saturday) • Day: 1-31 (day of the month) • Months:0 (January) –11 (December) • Year: since 1900 • Time: in millisecond since January 1, 1970 taxDay = new Date (2003,15,3,0,0,0);
Date methods For retrieving date and time value • dateVariable.getFullYear(); • dateVariable.getMonth(); • dateVariable.getDate(); • dateVariable.getDay(); • dateVariable.getHours(); • dateVariable.getMinutes(); • dateVariable.getSeconds(); taxDay = new Date (2003,15,3,0,0,0); taxDay.getMonth(); //returns 3
Arithmetic operators x=5+3; ‘x equals 8y=x++; ‘y equals 9z=-y ‘y equals -9 07_JSMath.htm
JavaScript built-in object for math calculations • Math.abs(numberVariable) • Returns the absolute value of numberVariable • Math.sin(numberVariable) • Calculates the sine of numberVariable, where numberVariable is an angle epressed in radians • Math.cos(numberVariable) • Calculates the cosine of numberVariable, where numberVariable is an angle expressed in radians • Math.round(numberVariable) • Rounds the value of numberVariable to the closet integer • Math.ceil(numberVariable) • Rounds the value of numberVariable up to the next highest integer • Math.floor(numberVariable) • Rounds the value of numberVariable down to the next lowest integer • Math.random() • Returns a random number between 0 and 1
Addition vs Concatenation result = var1 + var2 • If both are number variables: • Adds var1 to var2 • Assigns the result to the variable result • result is a number variable • If at least one of the two is a string: • Concatenate var1 and var2 • Assigns the result to the variable result • result is a string variable
Assignment operators • This operators are used with any data type to assign a specific value to a variable x=5; ‘x equals 5x+=6; ‘x equals 11x-=2; ‘x equals 9x*=3; ‘x equals 27x/=9; ‘x equals 3
JavaScript functions • A function is used to group related, script statements together in reusable units. A function might perform actions or calculates a value • It consists of: • A function name: it identifies the function and it is used to call the function when needed) • A set of parameters: a list of variable names that will contain the values used by the function, grouped within () • A command block: a set of commands that are executed when the function is used. The commands are grouped within {} function function_name (par1, par2, ..){JavaScript commands}
Performing an action with a function • Define the function in the <HEAD> and always before the command that calls the function function showDate (date){document.write(“Today is “+date);} • Call (or run) the function when needed, passing the parameters by value. var ThisDay = “10/29/2002”;showDate(ThisDay); Today is 10/29/2002
07_JSFct2.htm Returning a value from a function • You can use a function to calculate a value • You need a return command and a variable at the end of the function’s command block function average(num1, num2){ var avrg = (num1+num2)/2; return avrg;} Declaring the function var x= 10;var y=30;var z= average(x,y);document.write(“the average is “+z); Function is calledParameters 10 and 30 are passedz =result of function
07_JSScope.htm Variable scope • The scope of a variable is the range of statements over which it is visible. • Local variables Any variable declared (var) within the body of a function, exists only within that function • Global variables are variables declared outside the body of a function.They are available through the script. • Any variable not explicitly declared using var is global
The window object and methods • The window object represents a browser window. Window methods are • window.alert("string“); Shows an alert window with text string, and 'OK' button • window.prompt(“string of character”, “default value”);Prompts user for input • Window.confirm(“string”);If the OK button is clicked, the confirm method returns the value “true” • window.close(); • window.open(URL, windowname);
07_JSStatusBar.htm Service functions • window.status status bar function changes the text displayed in the status bar (bottom left corner of the browser window)<a href=“http://www.cs.depaul.edu” onMouseover=“window.status=`CTI homepage`; return true”onMouseout=“window.status=“”>CTI</a> • document.lastModified reflects when the page was last modifiedvar modifiedDate=document.lastModified;document.write(modifiedDate);
function average(num1, num2){ var avrg = (num1+num2)/2; return avrg;} Average revisited firstNumber = window.prompt("Enter an integer","0"); secondNumber = window.prompt("Enter another","0"); x=parseInt (firstNumber); y=parseInt (secondNumber); var z= average(x,y); document.writeln(“First number “+x); document.writeln(“Second number “+y); document.writeln(“The average of x and y is “+z); Transform string input into an integer Call functionReturn average 07_JSAverage.htm 07_JSMathFct.htm