410 likes | 523 Views
Javascript. JavaScipt. A client-side scripting language Allows building dynamic user interfaces Dynamic HTML elements Client side animation Modify client view based on user input Ability to check user input before forwarding to the server NOTE: JavaScipt and Java are different
E N D
JavaScipt • A client-side scripting language • Allows building dynamic user interfaces • Dynamic HTML elements • Client side animation • Modify client view based on user input • Ability to check user input before forwarding to the server • NOTE: JavaScipt and Java are different • JavaScript is based on a standard ECMA scripting language, JavaScipt name adopted for marketing reasons (Java was starting to get hot at the time)
JavaScript Basic Concepts • JavaScript is an interpreted language • No need to compile the code • The language is dynamically-typed • No need to declare the type of a variable • The type of a variable can change over time • Need to be careful that the type is not changed accidentally by a programming mistake • Structured Programming constructs • Similar to C • Case-sensitive like C
Incorporating JavaScipt • • JavaScripts can be put in the <body> and in the <head> sections of an HTML page. • • To insert a JavaScript into an HTML page, we use the <script> tag. • • Inside the <script> tag we use the type attribute to define the scripting language. <html><body><script type="text/javascript"> /*...and so on.. */ </script></body></html>
Incorporating JavaScipt • Handling browsers that do not support Javascript <html> <body> <script type="text/javascript"> <!-- document.write("Hello World!"); //--> </script> <noscript> <h2>Your Browser doesn’t support JavaScript! </h2> </noscript> </body> </html> • use HTML comments so that browsers that do not support JavaScript do not display your code
Incorporating JavaScipt into an HTML • Javascript in the <head> section • By default, javascripts in a page is executed automatically when a page loads into the browser. • However, we want to have control over when our scripts will be executed. • Usually, we want them to be called when an eventis triggered. In order to do this, we can write our scripts inside a function.
Incorporating JavaScipt into an HTML • Javascript in the <head> section <html><head><script type="text/javascript"> function message(){ alert("This alert box was invoked by an onload event."); }</script></head><body onload="message()"></body></html> Put your functionsin the <head> section. In this way, they are all written in one place, and they do not interfere with page content.
Incorporating JavaScipt into an HTML • Javascript in the <body> section • <html> • <head> • </head> • <body> • <script type="text/javascript"> • document.write("My first JavaScript"); • </script> • </body> • </html> • If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.
Incorporating JavaScipt into an HTML • Javascript in the <head> and <body> sections • You can place an unlimited number of scripts in your document, so you can have scripts in both the <body> and the <head> sections.
External Javascript file • If you want to run the same JavaScript on several pages, without having to write the same script on every page, you can write a JavaScript in an external file. • Save the external JavaScript file with a .jsfile extension. • Note: The external script cannot contain the <script></script> tags! • To use the external script, point to the .jsfile in the "src" attribute of the <script> tag: <html><head><script type="text/javascript" src=“filename.js"></script></head><body></body></html>
JavaScript Programming Constructs • All standard C operators can be used in JavaScript • +, -, *, /, +=, -=, ==, !=, <, >, >=, <=, %, &&, ||, ! • Also can add strings (concatenate) • Str3= Str1+ Str2; • if, if … else, switch… case…, for …, while …, do … while • Can all be used as in C • The semicolon is optional (according to the JavaScript standard). It allows you to write multiple statements in one line.
Variables • JavaScript variables are used to hold values or expressions. • A variable can have a short name, like x, or a more descriptive name, like carName. • Rules for JavaScript variable names: • Variable names are case sensitive (y and Y are two different variables) • Variable names must begin with a letter or the underscore character • Note: Because JavaScript is case-sensitive, variable names are case-sensitive.
Variables • If you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. • If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
Variables • A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value. • You can declare JavaScript variables with the var statement: • var x; • varuserName=”Napoleon”; //use double quotes to assign a text value • If you assign values to variables that have not yet been declared, the variables will automatically be declared. • If you redeclare a JavaScript variable, it will not lose its original value. • var z=100; • var z; • If you add a number and a string, the result will be a string!
Comparison Operators • greeting=(visitor=="PRES")?"Dear President ":"Dear ";
JavaScript Functions • Functions declared as in C • But no data types • E.g. myfun(){ document.write(“myfunction”);} • Functions can take parameters • E.g. myfun(X){ document.write(“Value:”+X);} • Functions can return values • E.g. myfun(X,Y){ return X+Y;}
Popup Boxes • Alert Box • An alert box is often used if you want to make sure information comes through to the user. • When an alert box pops up, the user will have to click "OK" to proceed. • Confirm Box • A confirm box is often used if you want the user to verify or accept something. • When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. • If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. • Prompt Box • A prompt box is often used if you want the user to input a value before entering a page. • When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. • If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
JavaScript Arrays • Zero-indexed arrays • myArray = new Array(4); • Create and array of 4 elements • myList = new Array(“one”, “two”, “three”); • first = myArray[0]; • myArray.length • Returns length of array (number of elements) • pop() : Removes last element of array • push(“item1”, “item2”) : Adds items to the end of the array • shift(): Removes an item from the front of the array • unshift(“item1”): Adds items to the beginning of the array • concat(): Joins two or more arrays, returning a new array • join(delimiter): Joins the elements of an array into a string using the delimiter
Catching Errors • The try...catch statement allows you to test a block of code for errors. • We would want to test our codes properly before making it publicly accessible. • We can test our codes for any error by using the try and catch clauses. try{//Run some code here}catch(err){//Handle errors here}
Catching Errors • Throw statement • The exception can be a string, integer, Boolean or an object. • Note that throw is written in lowercase letters. Using uppercase letters will generate a JavaScript error! • The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages. Syntax: throw(exception)
Catching Errors • <html> • <body> • <script type="text/javascript"> • var x=prompt("Enter a number between 0 and 10:",""); • try • { • if(x>10){ • throw "Err1"; • } • else if(x<0){ • throw "Err2"; • } • else if(isNaN(x)) { • throw "Err3"; • } • } • catch(er) • { • if(er=="Err1“) { • alert("Error! The value is too high"); • } • if(er=="Err2“) { • alert("Error! The value is too low"); • } • if(er=="Err3“) { • alert("Error! The value is not a number"); • } • } • </script> • </body> • </html>
HTML Document Object Model • The HTML document is available to your javaScript code as an object tree. • The root of this tree is the documentobject. • All the elements in the document are built under this tree • You can refer to each element using its element ID or Name • specify a unique name or id for each element • We shall return to the Document Object Model later on when we look at XML.
Examples HTML DROP-DOWN LIST <select name="drink"> <option value="2.50"> Coffee <option value="2.25"> Hot Cocoa <option value="1.00"> Chai </select> drop-down list: name:drink property:selectedindex property:value
Examples HTML Submit button <input type=submit value="Order">
Examples HTML RADIO BUTTONS <input type="radio" name="sizef" value="1">Tall <input type="radio" name="sizef" value="1.5">Grand <input type="radio" name="sizef" value="2"> Super radio-buttons: name:sizef property:value property:checked property:length
Examples HTML TEXT FIELDS <input type="text" name="label" value=""> <input type=text name="totalf" value="">
Examples <body> <h2> Coffee shop </h2> <p> <form name="orderf" onsubmit="return addup(this);" action=""> <select name="drink"> <option value="2.50">Coffee <option value="2.25">Hot Cocoa <option value="1.00">Chai </select> <br> <input type="radio" name="sizef" value="1">Tall <input type="radio" name="sizef" value="1.5">Grand <input type="radio" name="sizef" value="2"> Super <input type=submit value="Order"> <br> <br><input type="text" name="label" value=""> <input type=text name="totalf" value=""> </form> </body>
javascript <script type="text/javascript"> function addup(f) { var total; vartaxrate = .08 ; vardrinkbase; var opts; opts=f.drink; drinkbase = f.drink[opts.selectedIndex].value; varsizefactor; vari; var totals; vardp; for (i=0;i<f.sizef.length;i++) { if (f.sizef[i].checked) { sizefactor = f.sizef[i].value; } } total = sizefactor * drinkbase; total = total*(1 + taxrate); f.label.value="Total with tax"; f.totalf.value=total; totals = f.totalf.value + "00"; dp = totals.indexOf("."); if (dp<0) { f.totalf.value = "$" + f.totalf.value + ".00"; return false; } else { totals = "$" + totals.substr(0,dp+3); //control the number of decimal places f.totalf.value = totals; return false; } } </script> HTML elements Form: name:orderf drop-down list: name:drink property:selectedindex property:value radio-buttons: name:sizef property:value property:checked property:length text fields: name:label name:totalf property:value • string.indexOf(searchstring, start) • The indexOf() method returns the position of the first occurrence of a specified value in a string. • This method returns -1 if the value to search for never occurs.
Sending data to a server <form name="input" action="html_form_action.asp" method="get"> Username: <input type="text" name="user" /> <input type="submit" value="Submit" /></form> A submitbutton is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input:
Client-side (Browser) Objects • Window object: • Represents an open window in a browser. • Information about the windows this document is nested in. • not a W3C standard, but all major browsers support it.
Client-side (Browser) Objects • Navigator object: Information about the clients browser • You can access this object to learn about the name, version and platform where the browser was compiled. • It also tells us if the browser is Java-enabled. • not a W3C standard, but all major browsers support it. • History object: • Information about the URLs visited by the user within the browser’s window • window.history • For more information on the history object: https://developer.mozilla.org/en/window.history • Screen object: • Information about the clients screen (e.g. resolution, width and height of the screen – excluding the taskbar • not a W3C standard, but all major browsers support it. • window.screen
Client-side (Browser) Objects • Location object: • window.location • not a W3C standard, but all major browsers support it. • Information about the current URL • Hostname, port number, protocol, query portion
HTML DOM Collections • anchors[] • An anchor object represents an HTML hyperlink (bookmark, URL). • Any anchors with a name or id • applets[] • embeds[] • List of embedded objects, browser must have appropriate viewer • forms[] • images[] • links[] • Any anchors with an href
HTML DOM Properties • body • cookie • domain • Servers domain • referrer • URL of document that loaded current document • title • URL
HTML DOM Methods • getElementById("id") • Not W3C standard • getElementsByName("name") • open("mimetype"[,replace]) • write("str") • writeln("str") • close()
JavaScript Event Handling • As the Page loads and the user interacts with the web page events are generated • onload: of document body • onmouseover, onmouseout, onclick, ondblclick, onmousedown, onmouseup, onmousemove • onfocus, onresize • onkeydown, onkeypress, onkeyup • onsubmit, onchange
JavaScript Event Handling • Let’s look at an event handling example Javascript-16 - Events.html
How powerful is JavaScript? • This was taken from a news clip At the USENIX annual conference last month (June 2010), Gmail engineer Adam de Boor surprised the audience by noting that the company's Gmail service was written entirely in JavaScript, and that all of its code, around 443,000 lines worth, was written by hand. http://infoworld.com/d/developer-world/google-executive-frustrated-java-c-complexity-375 This recent news says it all! ;)
This was taken from a news clip He noted that while Java is more expressive, it is also more verbose. "At this point to me it's a matter of choice which language you use," de Boor said. JavaScript is one of a whole batch of languages -- others include Ruby and Python -- that have been developed over the past 10 years in response to the growing complexity of C++ and Java. While having a simpler syntax, such languages have their drawbacks as well, he argued. http://infoworld.com/d/developer-world/google-executive-frustrated-java-c-complexity-375
This was taken from a news clip These new languages tend to be slower, don't scale as well, and can harbor more errors, Pike elaborated. The languages tend to be interpreted rather than compiled, meaning the programs written in such languages aren't compiled before running, so tend to run slower as a result. They also tend to be dynamically typed, meaning programmers don't need to specify what type of data their variables will hold. "Dynamic typing is not necessarily good. You get static errors at run time which you really should be able to catch at compile time," he said. With all this in mind, Pike then described Go as an attempt to fuse the best attributes of both sets of languages. http://infoworld.com/d/developer-world/google-executive-frustrated-java-c-complexity-375
Summary • Main points to remember: • Dynamic web sites as opposed to static websites • Cascading style sheets • Javascript as a client-side programming language • HTML Document Object Model • Exercises: • Again, look at real web sites - this time those based on CSS and serve Javascript. Ask yourselves: What’s happening at the client side? What’s happening at the server side?