Functions: Function Square (Number) (Return Number Number)

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 18

Functions

• Functions are code sequences that “do something”


(perform a function) that you can call by name from inside
other code sequences.
• You can also give them different information to work with
(pass parameters) each time you call them.
• Syntax:
function fName(passedInfo)
{code to do the function}
• Example:
function square(number) {
return number * number
}
JavaScript - example
function testsalary(f) {
if (f < 200000)
document.write("Poor sod!")
else if (f == 200000)
document.write("Congratulations - you are an exact Mr.
Avarage")
else if ((f > 200000) && (f <= 500000))
document.write("High earner - HUH!.")
else document.write("Hello Rockefeller")
};

f=prompt("Input your salary","");


testsalary(f)
Control flow and value passing
• When the browser starts to execute lines of
code in a function, the function is said to
have been called.
• We say “control has passed to the function”
• Functions can call other functions
• Functions can call themselves (recursion)
• Functions can be called by events (onClick)
Built in functions (or methods)
• JavaScript has a wide variety of “built in”
functions available:
– document.write
– alert()
– confirm()
– prompt()
• Date and Time functions
– GetTime()
JavaScript is an Object-Based
Language
• The Objects JavaScript deal with are:
– Windows
– Forms
– Form Elements
• Buttons, and Radio Buttons
• Check Boxes
• Objects have their own Unique Names.
Objects
JavaScript enabled browsers have built-in objects which have
properties, events and methods which can be used by
JavaScript. For example:
Date Object String Object
GetDate() fontcolor()
GetTime() fontsize()
ToLowerCase()
GetDay() ToUpperCase()
GetMonth()
Window Object
Math Object alert(“message”)
confirm(“message”)
abs(number)
close()
log(number)
random()
JavaScript Dot Syntax

• Place Objects, Properties and Methods


together to get a better description of an
object or process.
– In JavaScript, these are separated by periods
AKA, dots or dot syntax.
– document.images.name
– window.status
Object & Properties
– document.write()
– forms.elements.radio.click()
Object & Methods
Form Validation Introduction
• The creation of forms was covered in the
HTML lectures.
• Review of form elements – most based on
the <INPUT TYPE = .. > tag
– Type = Text
– Type = Checkbox
– Type = Radio
– The exception - the drop down selection box
– <SELECT> <OPTIONS> </SELECT>
Form Validation (2)
• With HTML alone, you have no control over what
the user enters – and no interactivity.
• What do you do if the user skips a required field?
• What do you do if the user chooses incompatible
options
• The answer is - you create JavaScript validation
code to check the form values.
• But – how do you “get at” the data that has been
entered?
Form Validation (3)
• Because an HTML form is part of the BOM, we
use dot notation to access the Form elements (the
Form is an object composed of Element objects ;-)
• The syntax for accessing text entries:
– <INPUT TYPE = TEXT> is
– document.formName.elementName.value
– value is a keyword
– document can be skipped
– formName and elementName are the names you gave
your form and text input element
So – to get the value a user entered into a text field:
myTextVariable = formName.elementName.value
<HTML>
<HEAD>
Calculator Example
<TITLE>Square Calculator Function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide script from old browsers
function square(number) {
return number * number
}
// End script hiding from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
<H1>Square Calculator</H1><HR>
<FORM METHOD="POST" >
Enter a number <INPUT NAME="number1" TYPE="INT" VALUE="0">
<INPUT NAME="activate" VALUE="Calculate" TYPE="BUTTON"
OnClick="form.answer.value = square(form.number1.value)"><BR>
The square is
<INPUT NAME="answer" TYPE="INT" VALUE="0">
</FORM>
</BODY>
</HTML>
Handling JavaScript Events

• Events are actions that the user performs


while visiting your page.
– Submitting a form and moving a mouse over
an image that has a roll-over.
JavaScript Event Handlers

• JavaScript deals with events with


commands called event handlers.
– In JavaScript, if the user clicks on a button,
the onClick() event handler will take note of
the action and perform whatever duties it was
assigned.
• See the next slide for a listing of Event Handlers.
Event Handlers

Event What it Handles Event What it Handles


onAbort User aborted onLoad Object finished
loading the page loading
onBlur User left the object onMouseOver Cursor moved
over an object
onChange User changed the onMouseOut Cursor moved
object off an object
onClick User clicked on an onSelect User selected
object the contents of
an object
onError Script encountered onSubmit User submitted
an error a form
onFocus User made an onUnload User left the
object active window
Event Example
• Some Web designers like to have special
messages pop-up in the Status Bar when a
mouse passes over a Hypertext link.
– We will use a onMouseOver trick for this
one.
• Code is on the next slide.
onMouseOver Code inside the
<Body> Tag
• I'll use a Hyperlink to Hotbot and give it a
cool description for the status bar.

Note: You can't


have a Scrolling
Message and
this too!
Tips for Writing JavaScript

• Use comments throughout to help you understand the


program. <!-- comments -->
• Use indented text to make your code easier to read
and follow.
• JavaScript is case-sensitive, be careful.
• Include HTML comment tag to hide JavaScript from
older browsers that don’t support the code.
• Test your JavaScript program with several browsers
if possible.
JavaScript programming
• There are many JavaScripts on the Web that you can copy
and/or modify quite easily to fit your needs
• JavaScript programming often consist of:
– Finding effects on a page that you want to duplicate
– Locating the code that performs the effect – use View/Source in
your browser
– Cutting the code from the original page and embedding it in your
page
– Getting it to work in the new environment
• The time honored name for that process is HACKING

You might also like