IT - PowerPoint PPT Presentation

About This Presentation
Title:

IT

Description:

IT som v rkt j Bent Thomsen Institut for Datalogi Aalborg Universitet – PowerPoint PPT presentation

Number of Views:40
Avg rating:3.0/5.0
Slides: 62
Provided by: aau45
Category:
Tags: coding | looping

less

Transcript and Presenter's Notes

Title: IT


1
IT som værktøj
  • Bent Thomsen
  • Institut for Datalogi
  • Aalborg Universitet

2
Introduction to JavaScript
  • Bent Thomsen

3
What is a web script?
  • A program embedded in an HTML document
  • Scripts can be found multiple places in a
    document
  • There are multiple scripting languages
  • VBScript (Microsoft proprietary) interpreted only
    in IE unless a plug-in is installed
  • JavaScript far more common and universally
    interpreted in all browsers
  • Scripts make HTML into DHTML (dynamic HTML)

4
What is JavaScript?
  • A programming language to add interactivity to
    your Web page.

In the beginning there was HTML, and the folks at
Netscape saw that it was good. But it was
static interactivity was needed. People wanted
to enter information and get answers back. So the
Netscape folks decided that HTML should have a
helpmate, JavaScript. Unlike other programming
languages, JavaScript was built into the browser
and worked alongside HTML.
5
How does a script work?
  • A browser is a very complex, multi-function
    program
  • Using HTML syntax, the browser locates script
    statements inside the document
  • It hands the statements to a script interpreter
    that causes the browser to do what the statements
    (commands) tell it to do.

6
What is JavaScript
It is NOT Java or a dialect. It is a completely
different, interpreted language intended
to control the browser, typically to add dynamics
and animation to HTML. One of many programming
languages executed (possibly simultaneously) in
the browser!
Browser
VBScript Interpreter (compiler)
Control / HTML
Java Virtual Machine (JVM)
applet
HTML Interpreter (display formatting)
script
script
Control / HTML
HTML page
7
JavaScript is Not Java
  • Java is a full-featured programming language
    developed by Sun Microsystems.
  • Java's main use is to create applets, small
    programs that download over the Internet and run
    inside Web Browsers
  • Java applets are embedded in your Web page using
    the ltAPPLETgt tag.

8
Identifying JavaScript in an HTML page
  • Scripts can be found multiple places in a
    document
  • Scripts are placed between ltSCRIPTgtlt/SCRIPTgt
    tags.
  • The ltSCRIPTgt tag can be attributed with language
  • ltSCRIPT LANGUAGEJavaScriptgt
  • Script containers ltSCRIPTgtlt/SCRIPTgt can be
    found
  • In the ltHEADgt of the document in the ltSCRIPTgt
    lt/SCRIPTgt container
  • Anyplace in the ltBODYgt of the document in a
    script container
  • In-line code in various tags throughout the
    document
  • Usually associated with tags that support events
    such as ltIMGgt and form elements
  • The code describes what to do for a given event
  • Line(s) of script in quotes following the event
    name as an attribute of the tag

9
Hiding Your Script
  • You can hide your JavaScript program from
    browsers that cannot support them. Use this
    syntaxltSCRIPT LANGUAGEJavaScriptgtlt!---hide
    this script from browsers that dont support
    JavaScript JavaScript commands//Stop
    hiding from other browsers ---gtlt/SCRIPTgt

10
JavaScript Programs consists of
  • Values
  • Variables
  • Operators
  • Commands
  • Control Flow operations
  • Input/Output
  • Functions
  • Objects

11
Values
  • JavaScript recognizes
  • strings
  • numbers (integer and decimal)
  • boolean
  • Null value assigned using keyword null
  • x 100 integer
  • y 200 string
  • z true boolean

12
Variables
  • A variable is a place in the computers memory
    where information (values) are stored.
  • In programming languages, the storage places have
    names.
  • You access the value in the storage place by its
    name.

13
Variables
  • JavaScript variables are not explicitly defined
    (loosely typed language).
  • barWidth 50
  • Conversions are done automatically.
  • Variables must start with a letter or underscore.
  • To use the value of a JavaScript variable as an
    attribute in HTML, start with an ampersand ()
    and end with a semicolon ()
  • ltHR WIDTH"barWidth" ALIGN"LEFT"gt

14
Example
ltHTMLgt ltHEADgt ltSCRIPT LANGUAGE"JavaScript"gt lt!---
Hide script from old browsers. document.write("He
llo World!") barWidth 50 // End the hiding
here. --gt lt/SCRIPTgt lt/HEADgt ltBODYgt ltHR
WIDTH"barWidth" ALIGN"LEFT"gt Good-bye! lt/BO
DYgt lt/HTMLgt
15
The result
16
JavaScript Variables
  • JavaScript variable names must begin with a
    letter and cant contain unusual characters such
    as or
  • JavaScript variables are polymorphic HUH?
    that is, they can contain any type of information
  • Numbers
  • Strings
  • Object references (such as images!)
  • Variables in most other languages are more
    strictly typed

17
JavaScript Variables
  • Use to place a value into a variable
  • myNumber 12
  • (places the number 12 in the memory location
    named myNumber)
  • myString Hello World!
  • Strings are lines of characters delimited by
    single or double quotes
  • myObjAnImage C/pics/tower.jpg
  • Document.write myNumber ? (prints 12 onscreen)
  • yourNumber 10
  • myNumber yourNumber
  • Document.write myNumber ? (prints 10 onscreen)

18
Sending Output
  • JavaScript provides two commands to display text
    on a Web page the document.write() and
    document.writeln() commands. Here is the syntax
  • document.write(text here)
  • document.writeln(text here)
  • For example document.write(Hello World!)

19
Simple Input/Output
  • alert(Hello World)
  • confirm(Are you sure you want to delete?)
  • prompt(Enter your name?, )

20
JavaScript Commands
  • A command in any computer language is a
    reserved word such as write
  • or reserved symbol such as or
  • that tells the computer to do something
  • Change variable values
  • Direct the control flow
  • Manipulate I/O
  • Manipulate the O/S

21
JavaScript statements and code sequences
  • A statement is a syntactically correct command
  • A line is series of syntactically correct
    statements separated by semicolons ltgt and ending
    in a line-feed/carriage return
  • A code sequence is a series of lines which are
    executed left to right, top to bottom

22
Example
SomeVarSomeValue SomeOtherVarSomeOtherValue Te
st (SomeVar SomeOtherVar) Document.write(It
is Test that ) Document.write(SomeVar
is equal to SomeOtherVar)
23
Flow Control
  • if (condition)
  • code to be executed
  • else
  • code to be executed
  • for (i 0 i lt 10 i)
  • code to be executed
  • while (condition)
  • code to be executed

24
Selection (choosing alternatives)
  • if (statement in brackets is true) then
  • Do stuff in curly braces
  • else if (statement in brackets is true) then
  • Do stuff in curly braces
  • else if . . .
  • else
  • Do stuff in curly braces
  • Note that the first if has no else and the
    last else has no if!

25
Selection example
  • A simple program specification calling for
    conditionals and Boolean logic
  • Were going to input a salary figure
  • if lt 200K/yr then write Poor sod!
  • if exactly equal 200K/yr write Congratulations -
    you are an exact Mr. Average
  • if gt 200K and lt 500K then write High earner -
    HUH!.
  • if gt 500K/yr then write Hello Rockefeller

26
First, Comparison Operators
  • Equality
  • NOTE! JavaScript like C, C and Java to
    name only a few uses double equals to check for
    equality
  • A single equal sign is the assignment operator

27
Comparison Operators
  • Greater than (works for numbers and strings) gt
  • Less than lt
  • Combinations
  • Greater than or equal to gt
  • Less than or equal to lt

28
Logical (Boolean) Operators
  • To do the complex comparison
  • If gt 200K and lt 500K then write High earner
    HUH!.
  • Logical operators are required
  • AND (i.e. if A is true AND B is true)
  • OR (i.e. if A is true OR B is true)

29
JavaScript code
if (f lt 200000) document.write("Poor
sod!") else if (f 200000) document.write("Con
gratulations - you are an exact Mr.
Average") else if (f gt 200000 f lt 500000)
docuemnt.write("High earner - HUH!.") else
document.write("Hello Rockefeller")
30
Logical (Boolean) Operators (2)
  • The last logical operator is NOT ? !
  • i.e. if salary plus bennies is not gt 800K then I
    dont care.
  • If !((salary bennies) gt 800000) then . . .
  • Notice the ! comes first and applies to the
    entire expression in parentheses read it as
    if NOT salary plus bennies greater than . . .

31
Operators
  • Assignment Operator
  • -
  • /
  • Equality Operators
  • !
  • gt
  • gt
  • lt
  • lt
  • Other Operators
  • -
  • /
  • --
  • -
  • ltlt
  • gtgt
  • !

32
Loops
  • A loop is a piece of code that repeats multiple
    times.
  • It saves repetitive coding and all languages have
    looping facilities.
  • The alternative is called in-line code

33
While Loops
  • the while statement syntax is
  • while (condition)
  • code to be executed
  • Example
  • x1
  • while (x lt 10)
  • document.writeln(x is x)
  • x x 1
  • //could have used x1 or X

34
For Loops
  • JavaScript uses (mostly) the for statement.
  • the for statement syntax is
  • for (initialization code
  • loop test code
  • loop increment code)
  • code that gets repeated until the loop test is
    false

35
Arrays
  • A variable is a space in memory in which to store
    information
  • An array is a group of variables all called by
    the same name, but with different numbers
  • Images new array
  • Images1 i1.url
  • Images2 12.url
  • Document.write images1

36
Arrays (2)
  • Arrays are numbered starting with 0
  • Although you must specify an array dimension
    initially, you can change the dimension by
    storing something in a higher numbered element
  • myArray new array(3)
  • myArray new array (Tom, Dick, Harry)
  • myArray4 Fred

37
Loops and Arrays
  • Arrays and loops are made for each other
  • Arrays can be loaded using loops
  • Arrays can be searched using loops
  • for (i0ilt4,i)
  • if (myArrayiDick)
  • document.writeln myArrayi

38
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

39
Functions (2)
  • function fName(passedInfo)
  • code to do the function
  • fName is any valid JavaScript name
  • passedInfo can be a comma delimited list of
    values (valOne, valTwo, myString)
  • Any values in passedInfo are available to any
    code for the function they DO NOT need to be
    declared

40
JavaScript - example
function testsalary(f) if (f lt 200000)
document.write("Poor sod!") else if (f
200000) document.write("Congratulations - you
are an exact Mr. Avarage") else if ((f gt 200000)
(f lt 500000)) document.write("High earner -
HUH!.") else document.write("Hello
Rockefeller") fprompt("Input your
salary","") testsalary(f)
41
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)

42
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()

43
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.

44
Objects
JavaScript enabled browsers have built-in objects
which have properties, events and methods which
can be used by JavaScript. For example
  • Date Object
  • GetDate()
  • GetTime()
  • GetDay()
  • GetMonth()
  • Math Object
  • abs(number)
  • log(number)
  • random()
  • String Object
  • fontcolor()
  • fontsize()
  • ToLowerCase()
  • ToUpperCase()
  • Window Object
  • alert(message)
  • confirm(message)
  • close()

45
The Browser Object Model
  • You want to use JavaScript to dynamically change
    different properties of the browser, such as link
    colors, border widths, etc., etc.
  • How would you describe all the hundreds of
    properties in a way that was understandable and
    could be easily expressed in JavaScript?
  • Its called the BROWSER OBJECT MODEL (BOM)

46
JavaScript Objects have properties
  • In JavaScript, a Window Object has a Property
    called a Title.
  • A Form Object's Property could be a Check Box.

47
JavaScript Objects have Methods
  • The things that Objects do are called Methods.
  • Here a few Methods that JavaScripts Objects can
    do
  • buttons click()
  • windows open()
  • text can be selected()
  • The parentheses are referring to a method rather
    than a property.
  • Think of Objects and Properties as Nouns and
    Methods as Verbs.

48
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
  • document.write()
  • forms.elements.radio.click()

Object Properties
Object Methods
49
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.

50
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.

51
Event Handlers
52
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.

53
onMouseOver Code inside the ltBodygt 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!
54
Form Validation Introduction
  • The creation of forms was covered in the HTML
    lectures.
  • Review of form elements most based on the
    ltINPUT TYPE .. gt tag
  • Type Text
  • Type Checkbox
  • Type Radio
  • The exception - the drop down selection box
  • ltSELECTgt ltOPTIONSgt lt/SELECTgt

55
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?

56
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
  • ltINPUT TYPE TEXTgt 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

57
Form Validation (4)
  • The value entered into ltTEXTAREAgt tag (a textbox)
    is determined the same way.
  • myTextBoxVar formName.textBoxName.value
  • Where textBoxName is the name of the TEXTAREA
    element on the form
  • If you enter CRs in a TEXTAREA, they are
    retrieved. Otherwise multi-line (wrapped around)
    entries are treated as a single long string
    without line breaks (in IE) .

58
Calculator Example
ltHTMLgt ltHEADgt ltTITLEgtSquare Calculator
Functionlt/TITLEgt ltSCRIPT LANGUAGE"JavaScript"gt lt!
-- Hide script from old browsers function
square(number) return number
number // End script hiding from old browsers
--gt lt/SCRIPTgt lt/HEADgt ltBODYgt ltH1gtSquare
Calculatorlt/H1gtltHRgt ltFORM METHOD"POST" gt Enter a
number ltINPUT NAME"number1" TYPE"INT"
VALUE"0"gt ltINPUT NAME"activate"
VALUE"Calculate" TYPE"BUTTON" OnClick"form.answ
er.value square(form.number1.value)"gtltBRgt The
square is ltINPUT NAME"answer" TYPE"INT"
VALUE"0"gt lt/FORMgt lt/BODYgt lt/HTMLgt
59
Tips for Writing JavaScript
  • Use comments throughout to help you understand
    the program. lt!-- comments --gt
  • 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 dont support the code.
  • Test your JavaScript program with several
    browsers if possible.

60
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

61
Opgaver og kursusmateriale
http//www.cs.auc.dk/bt/FIT/index.htm
Happy Hacking
Write a Comment
User Comments (0)
About PowerShow.com