350 likes | 481 Views
Introduction to Javascript. Peter Atkinson. Objectives. To understand and use appropriately some of the basic elements of Javascript: alert and prompt methods window.write method string, number and Boolean variables functions array objects date objects conditionals multiple conditionals
E N D
Introduction to Javascript Peter Atkinson
Objectives • To understand and use appropriately some of the basic elements of Javascript: • alert and prompt methods • window.write method • string, number and Boolean variables • functions • array objects • date objects • conditionals • multiple conditionals • while loop • for loop • objects, methods and events
Page Template <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> </head> <body> </body> </html>
Using Alert <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Greeting Page</title> </head> <body> <a href=“#” onclick=“alert(‘Hello’)”>Click here for greeting</a> </body> </html> Embedded Javascript
What is a Variable? • A variable is a container • Create a variable var myname • Creates a container called ‘myname’ • Put something in to the container by assigning a value to the variable using = myname = “Fred”
Create a Variable and Assign a Value • So you can create a variable and give it a value like this: var myname myname = “Fred” • But, Javascript lets you make a shortcut by creating a variable and assigning it a value at the same time: myname = “Fred”
Points to Notice • Javascript is case sensitive so: myName is a different variable to myname • At the end of every line of Javascript code you do not need to put a ; but put one anyway. From now on: myname = “Fred”; is correct • You can use double quotes “Fred” or single quotes ‘Fred’ as long as you use them consistently • Javascript is “weakly typed” so you do not need to specify what kind of data will be stored in your variable
Let’s Use a Variable <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Using a Variable</title> <script type="text/javascript" language="javascript"> var myname; myname = “Fred”; </script> </head> <body> <p><a href=“#” onclick=“alert(myname);”>Click for message telling you the name</a></p> </body> Hands On Rewite this page using document. write to write the name to the page when it loads
Types of Variable • String • When you specify a text variable it must be enclosed in quote marks eg. “Fred” • Number • Integer (no decimals) • Floating Point – has decimals • Boolean – true or false • eg. myanswer = (2 + 2 ==3) • myanswer contains the value false • Object
Manipulating Strings To join two strings, use the concatenation operator +: var mystring; mystring = “Flossie”; document.write(“My name is: “ + mystring); Hands On Put this code into an HTML page Modify it so that it obtains the user’s name using a prompt
Manipulating Number Variables Put this Javascript into a blank page: var mystring, mynumber, shownumber; mystring = "56"; mynumber = 44; shownumber = mystring + mynumber; document.write(shownumber); Hands On Alter this code using the parseInt() function so that it adds 56 and 44 and writes the result 100 to the page
Using Number Operators • Be careful how you use numeric operators • Examine this piece of code: var myanswer; myanswer = 1 + 2 * 3; document.write(myanswer); • Hands On • What number do you think will be written to the page • Test it. Were you right? If not, why not?
Arrays • An array is like a variable but it can hold more than one value at a time var beatleArray = new Array(); beatleArray[0] = “John”; beatleArray[1] = “Paul”; beatleArray[2] = “George”; beatleArray[3] = “Ringo”;
Arrays • Hands On • Write a piece of code using an array containing the names of your four best friends • Have your code write each of these pieces of data to your HTML page
Arrays Hands On – suggested solution <script language="javascript" type="text/javascript"> myFriends = new Array(); myFriends[0] = "John"; myFriends[1] = "Paul"; myFriends[2] = "George"; myFriends[3] = "Ringo"; document.write(myFriends[0] + "<br />"); document.write(myFriends[1] + "<br />"); document.write(myFriends[2] + "<br />"); document.write(myFriends[3]); </script>
What is a Function? • A function is a block of code that may be used over and over. • The structure of a function is: function functionName() { code that does something; } • So for example, a function that shows our greeting: function greeting() { alert(“Hello”); }
Using a Function Hands On: try this code <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Greeting Function</title> <script type="text/javascript" language="javascript"> function greeting() { alert("Hello"); } </script> </head> <body> <a href="#" onclick="greeting();">Click here for greeting</a> </body> What are the advantages of using a function?
Conditional if (test condition) { some code that executes if condition is true; } else { some other code that executes if condition is false; }
Example Conditional if (myage < 30) { document.write(“You are too young!”); } else { document.write(“You are too old!”); } • Hands On • Place this code in an HTML page with a prompt to collect the reader’s age
Operators Used in Conditionals • Comparison Operators == Tests if LHS is equal to RHS < Tests if LHS is less than RHS > Tests if LHS is greater than RHS <= Tests if LHS is less than or equal to RHS >= Tests if LHS is greater than or equal to RHS != Tests if LHS is not equal to RHS • Logical Operators &&AND both LHS and RHS must be true || OR LHS or RHS must be true ! NOT reverses condition
Using a Conditional • Hands On • Use a prompt to obtain a number from the user • Write some code to test the number using a comparison operator to return one of two messages • Try each of the comparison operators in turn • Put another prompt into your code to obtain a second number from the user • Write some code that tests both numbers at the same time using a logical operator
Multiple Conditional Hands On : try out this code switch (myBeatle) { case “John”: alert(“Just Imagine!”); break; case “Paul”: alert(“Sorry about the divorce!”); break; case “George”: alert(“You are sadly missed!”); break; case “Ringo”: alert(“Where are you now?”); break; default: alert(“You are not a Beatle!”) break; }
For Loop for (initialise; test; update) { do something; } For example, we could write out the contents of an array: myArray = new Array(“John”,”Paul”’”George”,”Ringo”); for (i = 0; i < 4; i++) { document.write(myArray[i] + “<br />”); } Hands On Try out this piece of code
For Loop • Hands On • Use prompts to collect data from the user and store it in an array • Write the contents of the array to an HTML page
While Loop • The while loop allows you to test a condition and keep looping while it is true while (test condition) { do something; }
While Loop Example • Hands On: try this code var gameon = true; var i = 0; while(gameon == true) { var myguess = prompt("Guess what number between 1 and 5 I am thinking of: ",""); if (myguess == "3") { gameon = false; alert("You got it right! It is 3."); i++; } else { alert("You got it wrong! Try again."); i++; } } document.write("You took " + i + " guesses!");
Function – Hands On • Using Javascript features that you have learned so far, write some code for this game: • User to pick a number from 1 to 5 • If user guesses correctly, the user wins • If user guesses incorrectly, user can guess again • User can keep on guessing until user gets it right • Page displays number of guesses the user had
Javascript Concepts • Object – a car • Attributes – colour, insurance group • Methods – drive, reverse • Events – start, stop, collision
Native Objects • There are a number of built-in objects in Javascript eg Date and Array • To create an Array eg. var myarray = new Array(); • To create a Date object: var thisdate = new Date(); • Methods of the Date object: getDate() getDay() getMonth() getFullYear() eg. mydate = thisdate.getDate() Hands On • Use the Date object and its methods to write today’s date to your HTML page in the format Tuesday 1 January 2007
Events • Applies to the window object • onload – when window opens • onunload – on moving to another page • eg. window.onload = myFunction; • Applies to all HTML elements • onmousedown – user depresses mouse button • onmouseover – user moves mouse onto element • onmouseout – user moves mouse off element • onclick – user clicks mouse • eg. <p onclick=“myFunction();”>Some text</p>
Using Events • Hands On • Write a function that triggers an alert • Call the function from each of the events listed in turn
Finding Bugs • Hands On • You have been provided with a file HandsOn1.html that contains some common coding errors • Find the errors and correct them
Rollovers • Hands On • Copy the code from the Rollovers sheet into an HTML page • Write notes on the sheet explaining the use of the if…else feature used in this code
Cycling Banner • Hands On • Copy the code from the Cycling Banner sheet into an HTML page • Write notes on the sheet explaining the use of the setTimeout() feature used in this code
Objectives • To understand and use appropriately some of the basic elements of Javascript: • alert and prompt methods • window.write() method • string, number and Boolean variables • functions • array objects • date objects • conditionals • multiple conditionals • while loop • for loop • objects, methods and events