360 likes | 494 Views
ITBP 119 Algorithms and Problem Solving. Section 2.3 Variables workshop Section 2.4 Working with Objects. outline. Review Exercise Objects Properties Functions/methods. Review Exercise. Given two variables x and y, write code to swap the values between them. Test your code.
E N D
ITBP 119Algorithms and Problem Solving Section 2.3 Variables workshop Section 2.4 Working with Objects
outline • Review Exercise • Objects • Properties • Functions/methods
Review Exercise • Given two variables x and y, write code to swap the values between them. Test your code. • For example, suppose we have 2 variables var x = 10; var y = 100; We want you to write code that makes x contains 100 and y contains 10. But remember you do not know the value of each.
Idea of Swapping 2 Variable Values Step 2 X = Y; X Y Step 1 Z=X; Step 3 Y = Z Z
Objects • Objects :Objects are special variables that have properties and actions associated with them. • Real life is full of objects • Example: • Any student is an object • Properties are: name, date of birth, gpa, etc. • Actions: register for a course, drop a course, take the exam, attend class, tell me your GPA, tell me your age, etc. • UAE University is an object • Properties: president, date of foundation, location, etc. • Actions: admit students, graduate students, etc.
HTML page as an object • An html page is considered an object. • The name of this object is: document • document has many properties • Colors • Images • Forms • LastModified date and time • Actions associated with document object include: • Changing colors, images, forms, etc. • Writing to the document • …
How to access object properties and methods • We use period “.” for access variableName.property Variablename.method(…) • Example: suppose student ali is save under variable studentObj, then • studentObj.firstName = “ Ali”; • studentObj.lastName= “ Sallam”; • studentObj.register(“itbp119”); • studentObj.talk(“falah”); properties Methods/actions
Document.write method • This method (or function) is used to write to the document. • Example: • Create an HTML page • Use write method to insert your name to the document • Use write method to insert a headline of your name to the document • Use write method to insert an image to the document • Use write method to insert the link http://www.uaeu.ac.ae to the document • Change the background color to red • Extension: Try to change other properties such as fgColor, vlinkColor, and linkColor.
Structured or nested Objects UAE University College of IT ============== 1. Address=Maqam, Alain 2. Dean= “Dr. Boumediene” 3. Associate Dean = “Shuab” 4. Secretary = “Amirah” 5. buildingNo=MQC22 6. Departments College of Engineering citObj College of Science Software engineering Network engineering Computer science ….. Human Resources
Structured or nested Objects • An object might have other objects as properties. • Html page document is an object that might contain the following properties • <Img> tag: is an object and is a property of the html document. • Src is a property of the img object • Height is property of the img object • Width is a property of the img object • …. • <a> tag: is an object and is a property of the html document. • Href is a property of the <a> tag • innerHTML is a property of the <a> tag.
Accessing Object Properties • Accessing properties of the document object which are also objects • Use the getElementById method of the document variable/object to get the sub object variable var myImage = document.getElementById(“imgId”); • Using the variable, change/update the property
A moment with getElementById method var myImage = document.getElementById(“imgId”); • Is getElementById an asking or doing function? • How many parameter does it take?
Accessing document Object Example • Example • Insert an image under the body tag. Make sure to give an id for the img tag. • Display the current width of the picture and change it based on the user preferences. • Display the alt property of the picture and change it to be “ this is new alt” • Extension: try at home to change the height and src in a similar way.
Exercise: URL object • Create an HTML page. • Under the body tag, create the url http://www.google.com. Make sure to provide an id for the Url object. • In the script tag, • Prompt the user to enter new url text and change the innerHTML property to that. • Prompt the user to enter new link and change the link to that.
Exercise: Marquee object • Create an HTML page. • Under the body tag, create a marquee with the text “ this is UAE University”. Make sure to provide an id for the marquee object. • In the script tag, • Prompt the user to enter new text and change the innerText property to that. • Try to change other properties in the same way.
Functions • Function: is a sequence of statements that perform specific task. • Functions are used to reuse code over and over again without rewriting it. • In any language, there are 2 types: • Built-in functions: alert, prompt, document.write, etc. • User-defined functions: many functions you will define in this course
Function Syntax functionfunction_name ( parameters) { … body of the function } keyword Specify a name for the function Specify zero or More parameters Sequence of statements
Example • Write the function println that does exactly what the document.write do, except that it writes the text to the next line. function println ( msg ) { document.write ( msg + “ <br> “); }
Invoking a function • The code of the function does not get executed unless the user calls the function in the program. • We call or invoke user defined functions the same way we call built-in function.
Example: Asking functions that return a value • Write a function that computes and returns the value of the formula: For the following values: F(3.3), f(44), f(2), f(1.2) • Use prompt to enter a value, call the function, and display the result.
Example: Functions that has no parameters • Write a function that prompt the user with his/her year of birth and display the age. function displayAge ( ) { var year = prompt(“enter year of birth”,””); var age = 2008 – year; alert(“ your age is:” + age ); }
Events and Functions • Computer programs are full of events similar to the events occur in our life. • Normally there are actions associated with events. • Functions correspond to actions; • Examples: • Event: bell rang Action: go to class room • URL clicked Action: go to website • Button hit Action: make some computation
Example • In this example we will greet the user by saying hello over a url. • Add a url to the html page. • Create a function called greet in which it prompts the user with his/her name and then alerts “hello ….”. • Change the href in the url as follows: href=“javascript:greet()”
Example: Changing the picture by clicking on it • In this example we will learn how to handle the event of clicking on a picture. • Create HTML page • Insert an image tag with any picture you want. Make sure to give an id for the image tag. • Write a function that does the following: • Prompt the user with an image path • Change the src property of the above image to the new value • Change the image tag to handle the event of clicking the image
Example: inserting images to the document • In this example we will write a function that prompts the user with a picture path and inserts the image to the document. • Home Exercise • Change the function insertImage by adding an alt option to the image
Exercise 12 (section 2.4) • Add to your existing file the ability to change the background color of the page by modifying the bgColor property of the body tag. However you should provide a double click event handler (ondblclick) instead of a single click (onclick). (Note the capitalization which is inconsistent with conventions used elsewhere.)
More Built-in Functions • Math.pow(x,y) = x ^ y • Math.sqrt(x) = square root of x • Math.round(x) • And many others • Math.random() • Math.max(x,y) • Math.min(x,y) • Math.floor(x) • Math.abs(x) • Math.sin(x) • Math.cos(x) • Math.tan(x) • Math.exp(a)
Example: Euclidean Distance • Write a function the computes the Euclidean distance between 2 points in 2D. • The formula for distance is: • Test your function
Example: Manhattan Distance • Write a function the computes the Manhattan distance between 2 points in 2D. • The formula for distance is: • Test your function
2.5 Computing with String • String refers to any sequence of characters. • Example: • var str1 = “hello World !!!” ; • var phone = “00971-3-713-5584” ;
Strings are Objects • Properties: • Length • Actions/methods: • toUpperCase(): returns an upper case copy of the string • toLowerCase(): returns a lower case copy of the string • Replace(from character, to character). • Substring(start index, end index)
3 parts of any Computation input output Process
Examples • Read a sentence from the keyboard • Display how many characters the sentence has • Display the sentence in lower case • Display the sentence in upper case • Display the sentence such that you replace all spaces with dashes. Prompt() alert Compute upper case Computer lower case replace….
Example: safer passwords • Write a function that make your password safer as follows: • Covert a/A @ • Convert s/S $ • Convert o/O 0 • Convert g/G 8 • Convert i/I ! • Test your function.
Example: title property of the document object • Write a script such that whenever you double clicked on the HTML page, the current title of the page is displayed and then new title is entered. At all times, the new title should be in upper case.
Working with Numbers • parseInt ( str , radix): convert a string to a number. • parseFloat(str, radix): covert a string to a number. • toString(radix): convert decimal to another radix-base number.