Chris Panayiotou
JavaScript s role on the Web JavaScript Programming Language Developed by Netscape for use in Navigator Web Browsers Purpose make web pages (documents) more dynamic and interactive Change contents of document, provide forms and controls, animation, control web browser window, etc.
JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language i.e. lightweight programming language A JavaScript is usually embedded directly in HTML pages JavaScript is an interpreted language (means that scripts execute without preliminary compilation) Converts code to executable format each time it runs Converted when browser loads a web document JavaScript is supported by all major browsers Java and Javascript are not the same although they share some common syntax
Gives HTML designers a programming tool HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages Puts dynamic text into an HTML page A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page React to events A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element Can read and write HTML elements Can be used to validate data (e.g. form data) before it is submitted to a server
Typical programming elements: variables, operators, expressions, statements, definition of functions Connection to Web built-in functions (e.g., Date()) Document Object Model = names of things, properties, methods (e.g., document.write) events (e.g., onsubmit, onmouseover)
Inserting JavaScript into an HTML page <html> <body> <script type="text/javascript"> document.write("hello World!") </script> </body> </html> Note that semicolons are optional
JavaScript is usually placed in the HEAD section Make sure that the function is loaded before used <html> <head> <script type="text/javascript"> some statements </script> </head> <body> Some HTML </body> You can place any number of scripts in one page Can write code to a file and load the file <html> <head> <script src="xxx.js"></script> </head> <body> </body> </html>
Used to store information Variable name are case sensitive Must begin with a letter or the underscore Example: var strname = Chris Or strname = Chris The scope of variables is as usual Local within the functions Global (page level) if declared outside the functions
Operator Description Example Result + Addition - Subtraction * Multiplication / Division % Modulus (division remainder) ++ Increment -- Decrement x=2 x+2 x=2 5-x x=4 x*5 Arithmetic operators 4 3 20 15/5 3 5/2 2.5 5%2 1 10%8 2 10%2 0 x=5 x++ x=5 x-- x=6 x=4 Operator Example = x=y x=y Is The Same As += x+=y x=x+y -= x-=y x=x-y *= x*=y x=x*y /= x/=y x=x/y %= x%=y x=x%y Assignment Operators
Operator Description Example == is equal to!= is not equal > is greater than < is less than >= <= is greater than or equal to Comparison is less than or equal to 5==8 returns false 5!=8 returns true 5>8 returns false 5<8 returns true 5>=8 returns false 5<=8 returns true Operator Description Example && Logical and or! not x=6, y=3 (x < 10 && y > 1) returns true x=6, y=3 (x==5 y==5) returns false x=6, y=3!(x==y) returns true
Writing formatted text <html> <body> <script type="text/javascript"> document.write("<h1>hello World!</h1>") </script> </body> </html>
As in Java Example: txt1= What a very txt2= nice day! txt3=txt1 + + txt2 txt3 contains What a very nice day! Creating functions function myfunction(argument1,argument2,etc) { some statements Functions with returning values function result(a,b) { c=a+b return c Calling Functions myfunction(argument1,argument2,etc) Concatenation Functions
<script type="text/javascript"> // If the time on your browser // is less than 12, you will get // a Good morning greeting. var d=new Date() var time=d.gethours() if (time<10) { document.write("<b>good morning</b>") else { document.write("<b>good afternoon</b>") </script> If and If..Else statement while while (condition) { code to be executed do...while do { code to be executed while (condition) for for (initial; condition; increment) { code to be executed Loops
Switch <script type="text/javascript"> //You will receive a different greeting based on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date() theday=d.getday() switch (theday) { case 5: document.write("finally Friday") break case 6: document.write("super Saturday") break case 0: document.write("sleepy Sunday") break default: document.write("i'm looking forward to this weekend!") </script>
<html> <head> <title> JS1 </title> </head> <body> <a href="http://www.google.com " onmouseover="status= Happy Googling'; return true; > Google search </a> </body> </html> This is an event. This lets the hyperlink take place. Note single quotes inside double quotes
var input = prompt( What is your name?, Chris ); print("well hello " + (input dear )); If the user presses 'Cancel' or closes the prompt dialog in some other way without giving a name, the variable input will hold the value null or Both of these would give false when converted to a boolean The expression input "dear" can in this case be read as the value of the variable input, or else the string dear It is an easy way to provide a fallback value.
Similar to Java try { catch (error) { finally { statements function lastelement(array) { if (array.length > 0) return array[array.length 1] else throw Can not take the last element of an empty array. function lastelementplusten(array) { return lastelement(array) + 10 try { print(lastelementplusten([])); catch (error) { print( Something went wrong:, error) finally { print( Finished")
Document Object Model (DOM) Contains all HTML elements loaded in a web page Can be used by scripting languages to manipulate HTML on the fly DOM objects: Anchor (hyperlink) Body Button Checkbox Document Form Frame Frameset Image Link Location Password Radio Select Style Submit Table TableData TableHeader TableRow Text Textarea Window
<html> <head> <script type="text/javascript"> function myhref() { document.getelementbyid('myanchor').innertext="visit W3Schools" document.getelementbyid('myanchor').href="http://www.w3schools.com" </script> </head> <body> <a id="myanchor" href="http://www.microsoft.com">visit Microsoft</a> <form> <input type="button" onclick="myhref()" value="change URL and text"> </form> </body> </html>
<html> <head> <script type="text/javascript"> function showformelements(theform) { str="form Elements: " for (i=0; i<theform.length; i++) str+= \n +theform.elements[i].name alert(str) </script> </head> <body> <form> First name: <input type="text" name="fname" size="20"> <br /> Last name: <input type="text" name="lname" size="20"> <br /><br /> <input type= button name= button1 value= Display name of form elements onclick= showformelements(this.form) > </form> </body> </html>
<html> <head> <script type="text/javascript"> function formsubmit() { document.forms.myform.submit() </script> </head> <body> <form name="myform" action= sample2.asp" method="get"> Firstname: <input type="text" name="firstname" size="20"><br/> Lastname: <input type="text" name="lastname" size="20"><br/><br/> <input type="button" onclick="formsubmit()" value="submit"> </form> </body> </html>
<html> <head> <script type="text/javascript"> function validate() { x=document.myform at=x.email.value.indexof("@") if (at == -1) { alert("not a valid e-mail") return false </script> </head> <body> <form name="myform" action="tryjs_submitpage.htm" onsubmit="return validate()"> Enter your E-mail: <input type="text" name="email" size="20"> <input type="submit" value="submit"> </form> <p><b>note:</b> This example ONLY tests if the e-mail address contains an "@" character. A "reallife" code would have to test for punctuations, spaces and other things as well.</p> </body> </html>
http://www.javascript.com http://www.pageresource.com/jscript/ http://www.htmlgoodies.com/beyond/javascr ipt/index.php http://javascript.internet.com/ http://javascriptkit.com/ http://www.w3schools.com/js/default.asp Use Google
Create a page with JavaScript to do the following. These can all be on one page. Prompt the user for their name. Use a pop-up box to welcome the user by name. Display the current date on the page in the following format: October 30, 2000. Do not display the time. Do not "hard code" the date; if I load the page tomorrow, I should get a different date than if I load it today. Display the last modified date of the document. Put some useful advice, on any subject, in the status line of the browser. Display a message saying Good Morning if it is in the morning, Good Afternoon if it is in the afternoon, and Good Evening if it is in the Evening.
JavaScript Form Validation Exercise Create a form that includes 2 textboxes (one for name, one for email address), a textarea, a dropdown box (<select> tag), and a set of checkboxes. Format the form using a table. The ACTION attribute of the form tag should be to email the form results to your email address. Feel free to use a preexisting form rather than creating one for this exercise. Add JavaScript event handlers to the form to validate the form before it is emailed to you. If there is a problem, display the problem with the page in some way. Possible ways to do this are: a pop-up box displaying the problems in a new window in red text and having the user use the back button to go back to the original page displaying the problems in the current window at the top of the page in red text Validate that an entry has been made in each form element Validate that the email address contains an @ sign. If you have time and want to try something more, add a second drop down list and make this second one dynamic, i.e. make the choices that appear in the second drop down list depend on what choice is made in the first list.