Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise.

Similar presentations

Presentation on theme: "1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise."— Presentation transcript:

1 1 JavaScript James Ohene-Djan Sandbox 2013

2 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise static HTML pages JavaScript, 1995, Netscape (c/w HTML, 1991) Jscript, 1996, Microsoft ECMAScript, standardized version of Jscript JavaScript consists of lines of executable computer code and is usually embedded directly in HTML pages; JavaScript is an interpreted language; JavaScript can be used freely, and is supported by all major browsers (e.g. Netscape 4.5 + and Internet Explorer 4 + are augmented with JavaScript/Jscript interpreter – both of which are based on ECMAScript); Client-side.

3 3 What is JavaScript used for? Lots of things, including: –Dynamic page elements; –Link confirmation; –Client side calculations; –Animated buttons; –Browser detection; –Cookies; –Client side form validation; –Drop down menus. And more recently: –XML; –Scripted HTTP / Ajax (XMLHttpRequest); –Third party APIs

4 4 JavaScript basics JavaScript is usually embedded inside HTML documents using the tag. For example: JavaScript1 alert("My very first JavaScript");

5 5 JavaScript can be placed in either the head or the body of an HTML document. Scripts in the head section are executed only when they are called, or when a particular event occurs. JavaScript2 function aFunction() { alert("Thanks for that"); }

6 6 Scripts in the body section will be executed when the page loads. Here the document.write() method is used to dynamically output HTML text into an HTML document while it is being loaded into the browser JavaScript3 document.write(" In the body section ");

7 7 A web browser makes use of objects that can also be used in JavaScript programming. Each object has associated methods. Types of Object Objects of predefined classes Date, String, Math,…. Browser objects window, document,…. HTML objects link, form, button,…. …

8 8 Browser objects the starting point for most JavaScript programs. Initiated at browser startup examples window document location history navigator

9 9 window object – the window in which an html page loads methods –open(), close(), alert(), confirm(), prompt() example JavaScript4 Window 1 var newWindow; newWindow ="");

10 10 document object – the current html page methods –write(), open(), …. example JavaScript5 function docOpen() { document.write(" Hello World! ") } document.write(" This heading was created on-the-fly ");

11 11 location object - provides information about the origin of an html document, can be used to control the web page displayed by the browser. Methods –reload(), replace() attributes –host, href, pathname, port, protocol example JavaScript6 document.write("href= " + location.href + " "); document.write("pathname= " + location.pathname + " "); document.write("protocol= " + location.protocol);

12 12 navigator object – provides information about the users browser attributes –appCodeName, appName, appVersion, platform, userAgent example JavaScript7 Elements of the navigator object You are using the following browser: document.write(" "); document.write(" appCodeName ") document.write(" " + navigator.appCodeName); document.write(" "); document.write(" appName ") document.write(" " + navigator.appName); document.write(" "); document.write(" appVersion ") document.write(" " + navigator.appVersion); document.write(" "); document.write(" platform ") document.write(" " + navigator.platform); document.write(" "); document.write(" userAgent ") document.write(" " + navigator.userAgent); document.write(" ");

13 13 Prefined classes Belong to ECMAScript language standard Examples –Date, String, Math JavaScript8 var d = new Date() document.write(d.getDate()) document.write(".") document.write(d.getMonth() + 1) document.write(".") document.write(d.getFullYear())

14 14 Pop up windows - alert JavaScript9 Alert Example alert("This Site Is Not Suitable for Anybody Over the Age of 30");

15 15 Pop up windows - confirm JavaScript10 var reply; reply=confirm("Do you agree?"); if (reply) { alert("GOOD!"); } else { alert("NEVER MIND."); }

16 16 Pop up windows - prompt JavaScript11 username=prompt("Please enter your name","Enter your name here"); document.write(" Hello "+username+" Welcome to My Homepage ")

17 17 Variables and Operators Variables should be declared/defined using the var command. Variables should start with a letter and not contain any embedded spaces Assigning a value to an undeclared variable implicitly declares the variable (globally) Attempting to read the value of an undeclared variable causes a runtime error Values are most commonly assigned to variables using the = operator. JavaScript12 var username; var age; username="bjones"; age=32; document.write(username); document.write(age);

18 18 Arithmetic operators OperatorDescriptionExampleResult (y) +Additionx=5 y=x+3 8 -Subtractionx=5 y=12-x 7 *Multiplicationx=3 y=x*4 12 /Divisiony=16/53.2 %Modulus (division remainder) y=11%4 3 ++Incrementy=9 y++ 10 --Decrementy=23 y-- 22

19 19 Assignment operators ExampleIs The Same As x=y x+=yx=x+y x-=yx=x-y x*=yx=x*y x/=yx=x/y x%=yx=x%y

20 20 Comparison operators OperatorExplanation == equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to

21 21 Concatenate two strings using the + operator JavaScript13 text1="Welcome to" text2="my homepage." document.write(text1+text2); document.write(" ") document.write(text1+" "+text2);

22 22 Selection - if (condition) {action1} else {action2} JavaScript14 var d = new Date() var time = d.getHours() if (time < 12) { document.write(" Good morning ") } else { document.write(" Good afternoon ") }

23 23 Logical operators: AND, OR and NOT JavaScript16 cw1_grade=parseInt(prompt("Please enter your mark for cw1","1")); cw2_grade=parseInt(prompt("Please enter your mark for cw2","1")); if (cw1_grade && cw2_grade) { document.write("Well done you passed") } else if ((cw1_grade && !cw2_grade) || (!cw1_grade && cw2_grade)) document.write("Sorry, but you have failed - but only just"); else document.write("Sorry, you have failed big time");

24 24 Functions A function contains code that will be executed by an event or a call to that function. Functions are usually defined at the beginning of a.html file (in the head section) or as an external function in a separate file altogether (.js file). A function is defined with a name, values ("arguments") and statements. Functions can return a value to the calling expression.

25 25 Function example1 JavaScript17 function AddTwoNumbers(n1,n2) { answer=n1+n2 return(answer) } x=parseInt(prompt("Input first number","Number1 goes here")); y=parseInt(prompt("Input second number","Number2 goes here")); sum=AddTwoNumbers(x,y); document.write("The sum of the two numbers is "+sum+" ");

26 26 Function example1 JavaScript18 x=parseInt(prompt("Input first number","Number1 goes here")); y=parseInt(prompt("Input second number","Number2 goes here")); sum=AddTwoNumbers(x,y); document.write("The sum of the two numbers is "+sum+" "); function AddTwoNumbers(n1,n2) { answer=n1+n2 return(answer) }.html file javascript18.js

27 27 JavaScript Loops JavaScript19 INCHES CMs for (inches=1; inches<=30; inches=inches+1) { document.write(" "+inches+" "+(inches*2.54)+" "); }

28 28 JavaScript20 mile km mile=5 while (mile <= 100) { document.write(" "+mile+" "+(mile*1.6093)+" "); mile=mile+5 }

29 29 JavaScript Arrays JavaScript21 var cities = new Array() cities[0] = " london" cities[1] = " paris" cities[2] = " rome" for (i=0;i<cities.length;i++) { document.write(cities[i] + " ") }

30 30 Array - sort JavaScript22 var arr = new Array(6) arr[0] = "evans" arr[1] = "smith" arr[2] = "davies" arr[3] = "collins" arr[4] = "bowen" arr[5] = "thomas" document.write(arr + " ") document.write(arr.sort())

31 31 Last Updated Script JavaScript23 <!-- document.write(' Last updated : '); document.write(document.lastModified); document.write(' '); // --> Notice the use of HTML comment ( ) and JavaScript comment (//). These are used to prevent browsers that do not support JavaScript from writing the JavaScript code to the screen as text.

32 32 Browser Detection JavaScript24 alert(navigator.appName); if (navigator.appName.indexOf("Microsoft")!=-1) window.location.href = ""; else if (navigator.appName.indexOf("Netscape")!=-1) window.location.href = ""; else document.write("Browser "+navigator.appName+" not supported"); Makes use of the navigator object and the indexOf method. The navigator object holds name, version, etc. details of the browser. The indexOf() method returns the index value for where the parameter you give it first appears in the string it is invoked on, or the value -1 if the parameter (string) does not appear.

33 33 Animated Buttons JavaScript25 <a href="" onmouseOver="document.button1.src = 'computing-select.jpg'" onmouseOut="document.button1.src = 'computing-norm.jpg'">

34 34 Onclick event JavaScript27 SELECT A BACKGROUND COLOUR.

35 35 JavaScript28 function validate_email() { found_at=document.form1.email_address.value.indexOf("@") if (found_at == -1) { alert("Not a valid e-mail") return false } <form name="form1" action=form_ok.html" onsubmit="return validate_email()"> Enter your E-mail address: Form Validation – simple check for valid email

36 form_ok.html 36 Form Validation Example 1 Form has been sent

37 37 JavaScript29 function validate_email(e_address) { var emailFilter=/^.+@.+\..{2,3}$/; var illegalChars= /[\(\)\ \,\;\:\\\/\"\[\]]/ if (!(emailFilter.test(e_address))) { alert("Not a valid e-mail"); return false; } if (e_address.match(illegalChars)) { alert("Not a valid e-mail"); return false; } <form name="form1" action="" onsubmit="return validate_email(email_address.value)"> Enter your E-mail address: Form Validation – less simple check for valid email

38 38 JavaScrip30 function validate() {; if ( (parseInt(day) 31) ) { alert("day field invalid");; return false; } month=document.myForm.month.value.toLowerCase(); if ( (month!="jan") && (month!="feb") && (month!="mar") && (month!="apr") && (month!="may") && (month!="jun") && (month!="jul") && (month!="aug") && (month!="sep") && (month!="oct") && (month!="nov") && (month!="dec") ) { alert("invalid month"); document.myForm.month.focus(); return false; } year=document.myForm.year.value; current = new Date(); if (year != current. getFullYear()()) { alert("invalid year - only taking bookings for current year"); document.myForm.year.focus(); return false; } return true } Please supply required departure date Day Month Year Simple date validation

39 39 javascript31.html – will work in its own right (but slowly the first time you load it) javascript31 Pre-loading media

40 40 javascript32.html – preloads images, user might (or might not) visit display page javascript32 if (document.images) { img1 = new Image(); img1.src = ""; img2 = new Image(); img2.src = ""; img3 = new Image(); img3.src = ""; } Show Image Test out above – effect will only be properly demonstrated if you delete temporary internet files before executing preloadimage.html (in browser select Tools->Internet Options->Delete Files

Download ppt "1 JavaScript James Ohene-Djan Sandbox 2013. 2 What is JavaScript? JavaScript a scripting language developed to provide interactivity or behaviour to otherwise."

Similar presentations

Ads by Google