Published on

JavaScript is the scripting language of the Web.
JavaScript is used in web pages to add functionality, validate forms, communicate with the server, and much more.

Published in: Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. JAVASCRIPTLecturer, and Researcher at Thamar UniversityBy Eng: Mohammed HusseinByEng:MohammedHussein1Republic ofYemenTHAMAR UNIVERSITYFaculty of Computer Science&Information System
  2. 2. OUTLINE What is JavaScript? JavaScript Statements JavaScript Variables and Operators JavaScript Events JavaScript Try...Catch Statement JavaScript Browser (Navigator) JavaScript Cookies JavaScript Form ValidationByEng:MohammedHussein2
  3. 3. WHAT IS JAVASCRIPT? JavaScript is the scripting language of the Web. JavaScript is used in web pages to add functionality,validate forms, communicate with the server, and muchmore. JavaScript was designed to add interactivity to HTMLpages. A scripting language is a lightweight programminglanguage. JavaScript is usually embedded directly into HTML pages JavaScript is an interpreted language (means that scriptsexecute without preliminary compilation) Everyone can use JavaScript without purchasing a licenseByEng:MohammedHussein3
  4. 4. ARE JAVA AND JAVASCRIPT THE SAME? NO! Java and JavaScript are two completely different languages inboth concept and design! Java (developed by Sun Microsystems) is a powerful and muchmore complex programming language - in the same category as Cand C++. JavaScript is an implementation of the ECMAScript languagestandard. ECMA-262 is the official JavaScript standard. JavaScript was invented by Brendan Eich at Netscape (withNavigator 2.0), and has appeared in all browsers since 1996. The official standardization was adopted by the ECMAorganization (an industry standardization association) in 1997. The ECMA standard (called ECMAScript-262) was approved asan international ISO (ISO/IEC 16262) standard in 1998.ByEng:MohammedHussein4
  5. 5. WHAT CAN JAVASCRIPT DO? JavaScript gives HTML designers a programming tool - HTMLauthors are normally not programmers, but JavaScript is a scriptinglanguage with a very simple syntax! Almost anyone can put small"snippets" of code into their HTML pages JavaScript can react to events - A JavaScript can be set to executewhen something happens, like when a page has finished loading orwhen a user clicks on an HTML element JavaScript can read and write HTML elements - A JavaScript canread and change the content of an HTML element JavaScript can be used to validate data - A JavaScript can be usedto validate form data before it is submitted to a server. This saves theserver from extra processing JavaScript can be used to detect the visitors browser - AJavaScript can be used to detect the visitors browser, and - dependingon the browser - load another page specifically designed for thatbrowser JavaScript can be used to create cookies - A JavaScript can beused to store and retrieve information on the visitors computerByEng:MohammedHussein5
  6. 6. JS WRITING TO THE HTML DOCUMENT Unlike HTML,JavaScript is casesensitive. This example writes a<p> element withcurrent dateinformation to theHTML document. The lines between the<script> and </script>contain the JavaScriptand are executed by thebrowser.ByEng:MohammedHussein6<html><body><h1>My First Web Page</h1><script type="text/javascript">document.write("<p>" + Date() + "</p>");</script></body></html>
  7. 7. JS CHANGING HTML ELEMENTS To manipulate HTML elements JavaScript usesthe DOM method getElementById(). Thismethod accesses the element with the specified id.The browser will replace the content of the HTMLelement with id=“name", with the current dateByEng:MohammedHussein7<html><body><h1>My First Web Page</h1><p id=“name"></p><script type="text/javascript">document.getElementById(“name").innerHTML=Date();</script></body></html>
  8. 8. JAVASCRIPT STATEMENTS A JavaScript statement is a command to abrowser. The purpose of the command is to tell thebrowser what to do. This JavaScript statement tells the browser towrite "Hello Mohammed" to the web page The semicolon at the end is optional. Usingsemicolons makes it possible to write multiplestatements on one line. JavaScript statements can be grouped together inblocks { } brackets .ByEng:MohammedHussein8document.write("Hello Mohammed");
  9. 9. JAVASCRIPT COMMENTS The comment is used to prevent the executionof a single code line (can be suitable fordebugging) Single line comments start with //. Multi line comments start with /* and end with */.ByEng:MohammedHussein9<script type="text/javascript">//document.write("<h1>This is a heading</h1>"); ///* document.write("<p>This is a paragraph.</p>");document.write("<p>This is another paragraph.</p>"); */document.write("<p> comments </p>");</script>
  10. 10. SOME BROWSERS DO NOT SUPPORT JAVASCRIPT Browsers that do not support JavaScript, will displayJavaScript as page content. To prevent them from doing this, and as a part of theJavaScript standard, the HTML comment tag shouldbe used to "hide" the JavaScript. Just add an HTML comment tag <!-- before the firstJavaScript statement, and a --> (end of comment) afterthe last JavaScript statement. The two forward slashes at the end of comment line (//)is the JavaScript comment symbol. This preventsJavaScript from executing the --> tag.ByEng:MohammedHussein10<script type="text/javascript"><!--document.getElementById("demo").innerHTML=Date();//--></script>
  11. 11. JAVASCRIPT PLACE IN HTML JavaScripts can be put in the <body> and in the<head> sections of an HTML page. In <body>, the JavaScript is placed at the bottomof the page to make sure it is not executed beforethe <p> element is created as the perviousexample. In <head>, as we want to execute a JavaScriptwhen an event occurs, such as when a user clicksa button. When this is the case we can put thescript inside a function. Events are normally used in combination withfunctions (like calling a function when an eventoccurs).ByEng:MohammedHussein11
  12. 12. JAVASCRIPT IN <BODY> OR <HEAD> You can place anunlimited number ofscripts in your document,and you can have scriptsin both the body and thehead section at the sametime. It is a common practice toput all functions in thehead section, or at thebottom of the page. Thisway they are all in oneplace and do not interferewith page content.ByEng:MohammedHussein12<html><head><script type="text/javascript">function displayDate(){document.getElementById("demo").innerHTML=Date();}</script></head><body><h1>My First Web Page</h1><p id="demo"></p><button type="button"onclick="displayDate()">DisplayDate</button></body></html>
  13. 13. USING AN EXTERNAL JAVASCRIPT JavaScript can also be placed in external files. External JavaScript files often contain code tobe used on several different web pages. External JavaScript files have the fileextension .js.ByEng:MohammedHussein13<html><head><script type="text/javascript" src=“example.js"></script></head><body></body></html>
  14. 14. JAVASCRIPT VARIABLES A variable declared within a JavaScript functionbecomes LOCAL and can only be accessed withinthat function. (the variable has local scope). Variables declared outside a functionbecome GLOBAL, and all scripts and functions onthe web page can access it. Global variables are destroyed when you close the page. Rules for JavaScript variable names: Variable names are case sensitive (y and Y are twodifferent variables) Variable names must begin with a letter or theunderscore character.ByEng:MohammedHussein14var x=5;var Facultyname=“CSIT";
  15. 15. JAVASCRIPT OPERATORSOperator Description Example Result+ Addition x=y+2 x=7 y=5- Subtraction x=y-2 x=3 y=5* Multiplication x=y*2 x=10 y=5/ Division x=y/2 x=2.5 y=5% Modulus(divisionremainder)x=y%2 x=1 y=5++ Increment x=++y x=6 y=6x=y++ x=5 y=6-- Decrement x=--y x=4 y=4x=y-- x=5 y=4ByEng:MohammedHussein15
  16. 16. JAVASCRIPT ASSIGNMENT OPERATORSOperator Example Same As Result= x=y y=5 x=5+= x+=y x=x+y x=15-= x-=y x=x-y x=5*= x*=y x=x*y x=50/= x/=y x=x/y x=2%= x%=y x=x%y x=0ByEng:MohammedHussein16txt1="What a very";txt2="nice day";txt3=txt1+txt2;x=5+5;document.write(x);x="5"+"5";document.write(x);x=5+"5";document.write(x);x="5"+5;document.write(x);Adding Strings and NumbersThe + Operator Used on Strings
  17. 17. JAVASCRIPT COMPARISON OPERATORSOperator Description Example== is equal to x==8 is falsex==5 is true=== is exactly equal to (value andtype)x===5 is truex==="5" is false!= is not equal x!=8 is true> is greater than x>8 is false< is less than x<8 is true>= is greater than or equal to x>=8 is false<= is less than or equal to x<=8 is trueByEng:MohammedHussein17
  18. 18. LOGICAL OPERATORSOperator Description Example&& and (x < 10 && y > 1) is true|| or (x==5 || y==5) is false! not !(x==y) is trueByEng:MohammedHussein18Conditional OperatorJavaScript also contains a conditional operator that assigns a value to avariable based on some condition.Syntax variablename=(condition)?value1:value2Example greeting=(visitor==“Mohammed")?"Dear Dr.":"Dear ";If the variable visitor has the value of “Mohammed", then thevariable greeting will be assigned the value "Dear Dr." else itwill be assigned "Dear".
  19. 19. JS - IF...ELSE AND SWITCH STATEMENTS These are similar to PHP Statements if statement - use this statement to execute somecode only if a specified condition is true if...else statement - use this statement to executesome code if the condition is true and another code ifthe condition is false if...else if....else statement - use this statement toselect one of many blocks of code to be executed switch statement - use this statement to select oneof many blocks of code to be executedByEng:MohammedHussein19
  20. 20. JAVASCRIPT EVENTS Events are actions that can be detected by JavaScript. By using JavaScript, we have the ability to createdynamic web pages. Events are actions that can bedetected by JavaScript.ByEng:MohammedHussein20<html> <head><script type="text/javascript">function displayDate(){document.getElementById("name").innerHTML=Date();}</script></head><body><h1>My First Web Page</h1><p id="name"></p><button type="button" onclick="displayDate()">DisplayDate</button></body> </html>
  21. 21. ONLOAD AND ONUNLOAD EVENTS The onLoad and onUnload events are triggeredwhen the user enters or leaves the page. Both the onLoad and onUnload events are alsooften used to deal with cookies that should beset when a user enters or leaves a page. For example, you could have a popup asking for theusers name upon his first arrival to your page. Thename is then stored in a cookie. Next time thevisitor arrives at your page, you could have anotherpopup saying something like: "Welcome Ahmed!".ByEng:MohammedHussein21
  22. 22. ONSUBMIT EVENT The onSubmit event is used to validate ALLform fields before submitting it. Below is an example of how to use theonSubmit event. The checkForm() function will be called when theuser clicks the submit button in the form. If the fieldvalues are not accepted, the submit should becancelled. The function checkForm() returns eithertrue or false. If it returns true the form will besubmitted, otherwise the submit will be cancelled.ByEng:MohammedHussein22<form method="post" action=“ex.htm" onsubmit="return checkForm()">
  23. 23. ONFOCUS, ONBLUR AND ONCHANGE EVENTS The onFocus, onBlur and onChange events areoften used in combination with validation ofform fields. Below is an example of how to use theonChange event. The checkEmail() functionwill be called whenever the user changes thecontent of the field.ByEng:MohammedHussein23<input type="text" size="30" id="email" onchange="checkEmail()">
  24. 24. JAVASCRIPT TRY...CATCH STATEMENT The try...catch statement allows you to test a block ofcode for errors. The try block contains the code to be run, and thecatch block contains the code to be executed if an erroroccurs. Note that try...catch is written in lowercase letters. Usinguppercase letters will generate a JavaScript error! The try .. catch example uses a confirm box to displaya custom message telling users they can click OK tocontinue viewing the page or click Cancel to go to thehomepage. If the confirm method returns false, theuser clicked Cancel, and the code redirects the user. Ifthe confirm method returns true, the code does nothingByEng:MohammedHussein24
  25. 25. TRY...CATCH EXAMPLE<html> <head> <script type="text/javascript">var txt="";function message(){try{adddlert("Welcome guest!");}catch(err){txt="There was an error on this page.nn";txt+="Click OK to continue viewing this page,n";txt+="or Cancel to return to the home page.nn";if(!confirm(txt)){document.location.href="";}}}</script> </head><body><input type="button" value="View message"onclick="message()" /></body> </html>ByEng:MohammedHussein25OR
  26. 26. THE THROW STATEMENT The throw statement can be used together withthe try...catch statement, to create an exceptionfor the error. The throw statement allows you to create anexception. If you use this statement together withthe try...catch statement, you can control programflow and generate accurate error messages. The exception can be a string, integer, Boolean or anobject. Note that throw is written in lowercase letters. Usinguppercase letters will generate a JavaScript error!ByEng:MohammedHussein26
  27. 27. THROW EXAMPLE<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>ByEng:MohammedHussein27
  28. 28. JAVASCRIPT BROWSER (NAVIGATOR) The Navigator object contains information aboutthe visitors browser: name, version, and more. Browser Detection Browser should enabled JavaScript. However, there aresome things that just dont work on certain browsers -especially on older browsers. Sometimes it can be useful to detect the visitors browser,and then serve the appropriate information. Note: There is no public standard that applies to thenavigator object, but all major browsers support it.ByEng:MohammedHussein28
  29. 29. THE NAVIGATOR OBJECTByEng:MohammedHussein29<div id="example">Browser</div><script type="text/javascript">txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";txt+= "<p>Browser Name: " + navigator.appName + "</p>";txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";txt+= "<p>Platform: " + navigator.platform + "</p>";txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";document.getElementById("example").innerHTML=txt;</script>
  30. 30. JAVASCRIPT COOKIES A cookie is often used to identify a user. What is a Cookie? A cookie is a variable that is stored on the visitors computer. Each timethe same computer requests a page with a browser, it will send the cookietoo. With JavaScript, you can both create and retrieve cookie values. Examples of cookies: Name cookie - The first time a visitor arrives to your web page, he or shemust fill in her/his name. The name is then stored in a cookie. Next timethe visitor arrives at your page, he or she could get a welcome messagelike "Welcome Ana!" The name is retrieved from the stored cookie. Password cookie - The first time a visitor arrives to your web page, he orshe must fill in a password. The password is then stored in a cookie. Nexttime the visitor arrives at your page, the password is retrieved from thecookie Date cookie - The first time a visitor arrives to your web page, the currentdate is stored in a cookie. Next time the visitor arrives at your page, he orshe could get a message like "Your last visit was on Tuesday August 11,2008!" The date is retrieved from the stored cookieByEng:MohammedHussein30
  31. 31. CREATE AND STORE A COOKIE:STORE FUNCTION In this example we will create a cookie that stores the name of avisitor. First, we create a function that stores the name of the visitor in acookie variable: The parameters of the function hold the name of the cookie, thevalue of the cookie, and the number of days until the cookieexpires. we first convert the number of days to a valid date, then we addthe number of days until the cookie should expire. After that westore the cookie name, cookie value and the expiration date in thedocument.cookie object.ByEng:MohammedHussein31function setCookie(c_name , value, exdays){var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);var c_value=escape(value) + ((exdays==null) ? "" : ";expires="+exdate.toUTCString());document.cookie=c_name + "=" + c_value;}
  32. 32. CREATE AND STORE A COOKIE:RETURN FUNCTION This function makes an array to retrieve cookienames and values, then it checks if the specifiedcookie exists, and returns the cookie value.ByEng:MohammedHussein32function getCookie(c_name){var i,x,y,ARRcookies=document.cookie.split(";");for (i=0;i<ARRcookies.length;i++){x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);x=x.replace(/^s+|s+$/g,"");if (x==c_name){return unescape(y);}}}
  33. 33. CREATE AND STORE A COOKIE:DISPLAY FUNCTION The function that displays a welcome message if the cookieis set, and if the cookie is not set it will display a promptbox, asking for the name of the user, and stores theusername cookie for 365 days, by calling the setCookiefunction.ByEng:MohammedHussein33function checkCookie(){var username=getCookie("username");if (username!=null && username!=""){ alert("Welcome again " + username); }else{username=prompt("Please enter your name:","");if (username!=null && username!=""){ setCookie("username",username,365); }}}
  34. 34. COOKIE FULL EXAMPLE<html><head><script type="text/javascript">function getCookie(c_name){var i,x,y,ARRcookies=document.cookie.split(";");for (i=0;i<ARRcookies.length;i++){x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);x=x.replace(/^s+|s+$/g,"");if (x==c_name){ return unescape(y); }} }function setCookie(c_name,value,exdays){var exdate=new Date();exdate.setDate(exdate.getDate() + exdays);var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());document.cookie=c_name + "=" + c_value;}function checkCookie(){var username=getCookie("username");if (username!=null && username!=""){ alert("Welcome again " + username); }else{ username=prompt("Please enter your name:","");if (username!=null && username!=""){ setCookie("username",username,365); } }}</script> </head> <body onload="checkCookie()"> </body> </html>ByEng:MohammedHussein34F5
  35. 35. JAVASCRIPT FORM VALIDATION JavaScript can be used to validate data inHTML forms before sending off the content toa server. Form data that typically are checked by aJavaScript could be: has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?ByEng:MohammedHussein35
  36. 36. REQUIRED FIELDS The function below checks if a field has been leftempty. If the field is blank, an alert box alerts amessage, the function returns false, and the formwill not be submitted.ByEng:MohammedHussein36function validateForm(){var x=document.forms["myForm"]["fname"].value;if (x==null || x==""){ alert("First name must be filled out");return false; }}<form name="myForm" action=“Reg_form.asp"onsubmit="return validateForm()" method="post">First name: <input type="text" name="fname"><input type="submit" value="Submit"></form>
  37. 37. E-MAIL VALIDATION The function below checks if the content has the general syntax ofan email. This means that the input data must contain an @ signand at least one dot (.). Also, the @ must not be the first characterof the email address, and the last dot must be present after the @sign, and minimum 2 characters before the end.ByEng:MohammedHussein37function validateForm(){var x=document.forms["myForm"]["email"].value;var atpos=x.indexOf("@");var dotpos=x.lastIndexOf(".");if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){ alert("Not a valid e-mail address");return false; } }<form name="myForm" action="demo_form.asp"onsubmit="return validateForm();" method="post">Email: <input type="text" name="email"><input type="submit" value="Submit"></form>
  38. 38. REFERENCES