Top Banner
1 JavaScript
41

JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

Sep 03, 2019

Download

Documents

dariahiddleston
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

1

JavaScript

Page 2: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

2

Što je JavaScrpt? JavaScript je skriptni programski jezik,

osmišljen da doda interaktivnost na web stranice.

HTML dizajnerima daje programerski alat JS može reagirati na događaje JS može čitati i mijenjati sadržaj HTML

elemenata JS se može koristiti za analizu forme

podataka

Page 3: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

3

Kako uključiti JS u HTML stranice?

• Na 3 načinaSkripte u body dijeluSkripte body dijeluVanjski JavaScript

• Skripte napisane u body dijelu izvršiti će se dok se stranica učitava.

• Skripte napisane u head dijelu izvršiti će se tek kada ih pozovemo.

Page 4: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

4

Sintaksa JavaScript jezika• Varijable • Operatori :

Aritmetički : +,-,*,/,%,++,-- Operatori pridjele vrijednosti : =,+=,-=,+=,/=,%= Operatori usporedbe: ==,!=,<,>,>=,<= Logički operatori: &&,||,! String operator +

• Funkcije :function moja_funkcija (argument1,argument2, ... )

{ neke naredbe

return val}

Page 5: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

5

Izrazi za kontrolu toka• Uvjetne naredbe:

– if (izvršava se ako je vrijednost uvjeta true)– if...else (izvršava se jedan od dva bloka naredbi)– switch (jedan od više blokova naredbi)

• Naredbe ponavljanja– while – ponavlja određeni blok koda dok je uvjet

zadovoljen– do...while – blok koda se izvrši jednom, a tada se

ponavlja dok je zadovoljen uvjet– for – ponavlja set naredbi određen broj puta

Page 6: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

6

Klase ugrađene u JavaScript• Klasa:

metoda1()metoda2(lista parametara):povratna vrijednost…

(methods)

svojstvo1: tipsvojstvo2:tip….(properties)

Ime klase

Klasaobjekt:

Objekt je instanca klase!

Page 7: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

7

String• Upotreba jednostrukih i dvostrukih navodnika• Odabrati jednu od formi i koristiti je do krajaPrimjer:<INPUT TYPE=”checkbox ” NAME=”candy ”>Chocolate

result =‘<INPUT TYPE=”checkbox ” NAME=”candy ”>Chocolate ’result =“<INPUT TYPE=’checkbox ’ NAME=’candy ’>Chocolate

Page 8: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

8

String objekt

• Primjenom operatora + možemo slagati duge stringove

var newDocument =“”newDocument +=“<HTML><HEAD><TITLE>Life and

Times</TITLE></HEAD>”newDocument +=“<BODY><H1>My Life and Welcome to

It</H1>”newDocument +=“by Sidney Finortny<HR>”

Page 9: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

9

Posebni znakovi

• Dodavanje “inline characters” pomoću backslash (“ \ ”)

\” Double quote \’ Single quote (apostrophe) \\ Backslash \b Backspace \t Tab \n New line \r Carriage return \f Form feed

Page 10: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

10

Sintaksa

• Kreiranje string objektavar myString =new String(“characters ”)

Pristupanje static String property ili metodi objekta

String.property | method ([parameters ])

Pristupanje string property ili metodi objekta

string.property |method ([parameters ])

Page 11: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

11

Returns the number of characters in a stringlength

ExplanationProperties

Returns the Unicode of the character at a specified position

charCodeAt()

Returns the character at a specified positioncharAt()

Returns a string in boldbold()

Returns a string blinkingblink()

Returns a string in big textbig()

Returns a string as an anchoranchor()

ExplanationMethods

Page 12: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

12

Similar to indexOf and lastIndexOf, but this method returns the specified string, or "null", instead of a numeric value

match()

Returns a string as a hyperlinklink()

Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs. Note: This method starts from the right and moves left!

lastIndexOf()

Returns a string in italicitalics()

Returns the position of the first occurrence of a specified string inside another string. Returns -1 if it never occurs

indexOf()

Returns the character value of a UnicodefromCharCode()

Returns a string in a specified sizefontsize()

Returns a string in a specified colorfontcolor()

Returns a string as teletypefixed()

Returns two concatenated stringsconcat()

Page 13: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

13Converts a string to upper casetoUpperCase()

Converts a string to lower casetoLowerCase()

Returns a string as superscriptsup()

Returns the specified characters. 7,14 returns all characters from the 7th up to but not including the 14th (starts at 0)

substring()

Returns the specified characters. 14,7 returns 7 characters, from the 14th character (starts at 0)

substr()

Returns a string as subscriptsub()

Returns a string strikethroughstrike()

Splits a string into an array of strings split()

Returns a string as small textsmall()

Returns a string containing a specified character index

slice()

Returns an integer if the string contains some specified characters, if not it returns -1

search()

Replaces some specified characters with some new specified characters

replace()

Page 14: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

14

Examples• The length property

This example returns the number of characters in a string.

• The fontcolor() methodThis example returns a string in a specified color.

• The indexOf() methodThis example tests if a string contains a specified text and returns the position of where the text was found.

• The match() methodThis example tests if a string contains a specified text and returns the text if it was found.

• The substr() and substring() methodsThis example returns a specified part of a string.

• The toLowerCase() and toUpperCase() methodsThis example converts a string to lowercase and uppercase.

Page 15: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

15

Array objekt• Array objekt se koristi za pohranjivanje skupa vrijednosti

u varijabli jednog imena. • Svaka vrijednost je element niza i ima svoj indeks• Pojedinom elementu možemo pristupiti koristeći ime niza

i indeks željenog elementa• Indeks prvog elementa je 0• Novi niz kreiramo korištenjem ključne riječi new

var family_names=new Array(5)

• Unutar zagrada upisujemo očekivani broj elemenata

Page 16: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

16

Array object• Svakom elementu pridružujemo vrijednost na

sljedeći načinfamily_names[0]="Tove" family_names[1]="Jani" family_names[2]="Stale" family_names[3]="Hege" family_names[4]="Kai“

• Možemo dohvatiti podatke na sljedeći način:mother=family_names[0] father=family_names[1]

Page 17: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

17

Returns a sorted arraysort()

Returns a specified part of the arrayslice()

Returns the array reversed reverse()

Returns a string of all the elements of an array concatenated together

join()

Returns an array concatenated of two arrays

concat()

Returns the number of elements in an array. This property is assigned a value when an array is created

length

ExplanationMethods

Page 18: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

18

Examples• Put array elements into a string - join()

How to use the join() method to put all the elements of an array into a string.• Literal array - sort()�

How to use the sort() method to sort a literal array.• Numeric array - sort()�

How to use the sort() method to sort a numeric array.

Page 19: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

19

Date object• Objekt tipa Date koristi se za rad sa datumima i

vremenskom podacima• Instanca objekta stvara se korištenjem ključne

riječi new• Kreiranjem objekta bez dodatnih opcija, objekt

se inicijalizira na trenutno sistemsko vrijemevar my_date=new Date()

• Pomoću metoda Date objekta možemo dohvaćati informacije o vremenu, npr

• my_date.getDate()

Page 20: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

20

• Osim trenutnog vremena, objekt može biti inicijaliziran na bilo koji drugi datum:

var my_date=new Date("October 12, 1988 13:14:00") var my_date=new Date("October 12, 1988") var my_date=new Date(88,09,12,13,14,00) var my_date=new Date(88,09,12) var my_date=new Date(500)

new Date("Month dd, yyyy hh:mm:ss") new Date("Month dd, yyyy") new Date(yy,mm,dd,hh,mm,ss) new Date(yy,mm,dd) new Date(milliseconds)

PrimjerSintaksa

Page 21: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

21Returns the number of milliseconds since midnight 1/1-1970getTime()

Returns the millisecond of a Date object (from 0-999)getMilliseconds()

Returns the second of a Date object (from 0-59)getSeconds()

Returns the minute of a Date object (from 0-59)getMinutes()

Returns the hour of a Date object (from 0-23)getHours()

Returns the year of a Date object (from 0-99). Use getFullYear instead !!

getYear()

Returns the year of a Date object (four digits)getFullYear()

Returns the month of a Date object (from 0-11. 0=January, 1=February, etc.)

getMonth()

Returns the day of a Date object (from 0-6. 0=Sunday, 1=Monday, etc.)

getDay()

Returns the date of a Date object (from 1-31)getDate()

Returns a Date objectDate()

ExplanationMethods

Page 22: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

22

Returns the milliseconds of a Date object in universal time

getUTCMilliseconds()

Returns the seconds of a Date object in universal time

getUTCSeconds()

Returns the minutes of a Date object in universal time

getUTCMinutes()

Returns the hour of a Date object in universal time

getUTCHours()

Returns the four-digit year of a Date object in universal time

getUTCFullYear()

Returns the month of a Date object in universal time

getUTCMonth()

Returns the day of a Date object in universal time

getUTCDay()

Returns the date of a Date object in universal (UTC) time

getUTCDate()

Returns the time difference between the user's computer and GMT

getTimezoneOffset()

Page 23: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

23

Sets the year in the Date object (00-99)setYear()Sets the milliseconds after 1/1-1970setTime()Sets the second in the Date object (from 0-59)setSeconds()

Sets the month in the Date object (from 0-11. 0=January, 1=February)

setMonth()Set the minute in the Date object (from 0-59)setMinutes()

Sets the millisecond in the Date object (from 0-999)

setMilliseconds()

Sets the hour in the Date object (from 0-23)setHours()Sets the year in the Date object (four digits)setFullYear()

Sets the date of the month in the Date object (from 1-31)

setDate()

Returns a string date value that holds the number of milliseconds since January 01 1970 00:00:00

parse()

Page 24: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

24Converts the Date object to a stringtoString()

Converts the Date object to a string, set to the current time zone

toLocaleString()

Converts the Date object to a string, set to GMT time zone

toGMTString()

Sets the milliseconds in the Date object, in universal time (from 0-999)

setUTCMilliseconds()

Sets the seconds in the Date object, in universal time (from 0-59)

setUTCSeconds()

Sets the minutes in the Date object, in universal time (from 0-59)

setUTCMinutes()

Sets the hour in the Date object, in universal time (from 0-23)

setUTCHour()

Sets the year in the Date object, in universal time (four digits)

setUTCFullYear()

Sets the month in the Date object, in universal time (from 0-11. 0=January, 1=February)

setUTCMonth()

Sets the day in the Date object, in universal time (from 0-6. Sunday=0, Monday=1, etc.)

setUTCDay()

Sets the date in the Date object, in universal time (from 1-31)

setUTCDate()

Page 25: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

25

Examples• Date

Returns today's date including date, month, and year. Note that the getMonth method returns 0 in January, 1 in February etc. So add 1 to the getMonth method to display the correct date.

• TimeReturns the current local time including hour, minutes, and seconds. To return the GMT time use getUTCHours, getUTCMinutes etc.

• Set dateYou can also set the date or time into the date object, with the setDate, setHour etc. Note that in this example, only the FullYear is set.

• UTC timeThe getUTCDate method returns the Universal Coordinated Time which is the time set by the World Time Standard.

• Display weekdayA simple script that allows you to write the name of the current day instead of the number. Note that the array object is used to store the names, and that Sunday=0, Monday=1 etc.

• Display full dateHow to write a complete date with the name of the day and the name of the month.

• Display timeHow to display the time on your pages. Note that this script is similar to the Time example above, only this script writes the time in an input field. And it continues writing the time one time per second.

Page 26: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

26

Brojevi

• Operacije sa decimalnim, heksadecimalnim i oktalnim brojevima

• Decimalni ne smiju početi sa 0• Heksadecimalni broj počima 0x ili 0X• Oktalni brojevi počimaju sa 0 a slijede je

znamenke između 0 i 7

Page 27: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

27

Math object• Ugrađeni objekt Math uključuje matematičke

konstante i funkcije• Nije potrebno kreirati objekt prije korištenja• Npr:• r_number=Math.random()• r_number=Math.round(8.6) • Math se upotrebljava kada je operacija nad

brojevima složenija od obične aritmetičke operacije

Page 28: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

28

Math objekt• JS nije “strongly typed language”• Moramo sami paziti na tipove s kojim

radimo• Dopušta operacije sa različitim tipovima3 +4 =7 //integer result3 +4.1 =7.1 //floating-point result3.9 +4.1 =8 //integer result

Page 29: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

29

Svojstva (varijable)PROPERTIE VALUE DESCRIPTIONMath.E 2.718281828459045091 Euler’s

constantMath.LN2 0.6931471805599452862 Natural log

of 2Math.LN10 2.302585092994045901 Natural log

of 10Math.LOG2E 1.442695040888963387 Log base-2

of EMath.LOG10E 0.4342944819032518167 Log base-

10 of EMath.PI 3.141592653589793116 πMath.SQRT 1_2 0.7071067811865475727 Square root of

0.5Math.SQRT2 1.414213562373095145 Square root of 2

Page 30: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

30

MetodeMethod syntax Returns Math.abs(val ) Absolute value of valMath.acos(val ) Arc cosine (in radians) of valMath.asin(val ) Arc sine (in radians) of valMath.atan(val ) Arc tangent (in radians) of valMath.atan2(val1 ,val2 ) Angle of polar coordinates x

and yMath.ceil(val ) Next integer greater than or

equal to valMath.cos(val ) Cosine of valMath.exp(val ) Euler’s constant to the power

of valMath.floor(val ) Next integer less than

or equal to valMath.sin(val ) Sine (in radians) of valMath.max(val1 ,val2 ) The greater of val1 or val2

Page 31: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

31

Examples• Round

How to round a specified number to the nearest whole number

• Random numberThe random method returns a random number between 0 and 1

• Random number from 0 to 10How to find a random number from 0 to 10 using the random() and round() methods.

• Max numberHow to test which of two numbers, has the higher value. 

• Min numberHow to test which of two numbers, has the lower value.

Page 32: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

32

HTML DOM (Document Object Model)

• The W3C Document Object Model (DOM) is a platform and language neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.

• HTML DOM je Document Object Model za HTML• HTML DOM je neovisan o platformi i jeziku• HTML DOM definira standardni skup objekata za HTML,

i standardni način pristupa HTML dokumentu• HTML DOM je W3C standard

Page 33: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

33

DOM• Kad učitamo stranicu u preglednik, on stvori

određen broj objekata s obzirom na sadržaj stranice.

• Objekti koje svaka stranica ima su:– window objekt naviše razine, sadrži svojstva

koja se odnose na čitav prozor– location sadrži svosjtva tekuće URL adrese– history sadrži svojstva URL-ova koje je

korisnik prije posjetio– document sadrži svojstva sadržaja tekućeg

dokumenta, kao što su naziv, pozadinska boja i formular

Page 34: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

34

Hijerarhija objekata klijenta

window

self,...navigatorframes[]locationhistorydocumentscreen

forms[]anchors[]links[]images[]applets[]embeds[]

elements[]such as theinput objects

and thetextareaobject

Level 0 DOM

This is a partial diagram

Page 35: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

35

Document

• Document je najkorisniji objekt. Zbog toga što ima write i writeln metode može generirati HTML kod, pa tako imamo:

• document.write(“Dobar dan!")• što daje izlaz:

Dobar dan!

Page 36: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

36

• Ukoliko definiramo nekoliko tekstualnih elemenata:<FORM NAME="iskaznica">

<input type="text " name="ime" size=20>

<input type="text" name="dob" size=3>• ovi elementi se zrcale u JavaScript objekte: document.iskaznica.ime i

document.iskaznica.dob koje možemo koristiti bilo gdje, nakon što je formular

definiran.• Možemo ih ispisati u skripti, koju pišemo nakon što je

formular definiran:<SCRIPT>

document.write(document.iskaznica.ime)

document.write(document.iskaznica.dob)

</SCRIPT>

Page 37: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

37

Objekti HTML DOM-a

Represents a checkbox on an HTML form. For each instance of an HTML <input type="checkbox"> tag on an HTML form, a Checkbox object is created

Checkbox

Represents a push button on an HTML form. For each instance of an HTML <input type="button"> tag on an HTML form, a Button object is created

ButtonRepresents the body of the document (the HTML body)BodyRepresents an HTML basefont elementBasefontRepresents an HTML base elementBase

Represents an area of an image-map. An image-map is an image with clickable regions

Area

Represents an HTML applet element. The applet element is used to place executable content on a page

Applet

Represents an HTML a element (a hyperlink)AnchorDescriptionObject

Page 38: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

38Represents an HTML inline-frameIframe

A predefined object which can be accessed through the history property of the Window object. This object consists of an array of URLs. These URLs are all the URLs the user has visited within a browser window

History

Represents a hidden field on an HTML form. For each instance of an HTML <input type="hidden"> tag on a form, a Hidden object is created

Hidden

Represents an HTML framesetFramesetRepresents an HTML frameFrame

Forms are used to prompt users for input. Represents an HTML form element

Form

For each instance of an HTML <input type="file"> tag on a form, a FileUpload object is created

FileUpload

Represents the state of an event, such as the element in which the event occurred, the state of the keyboard keys, the location of the mouse, and the state of the mouse buttons

Event

Used to access all elements in a pageDocument

Page 39: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

39Represents a selection list on an HTML form. For each instance of an HTML <select> tag on a form, a Select object is created

Select

Automatically created by the JavaScript runtime engine and it contains information about the client's display screen

Screen

Represents a reset button on an HTML form. For each instance of an HTML <input type="reset"> tag on a form, a Reset object is created

Reset

Represents radio buttons on an HTML form. For each instance of an HTML <input type="radio"> tag on a form, a Radio object is created

Radio

Represents a password field on an HTML form. For each instance of an HTML <input type="password"> tag on a form, a Password object is created

Password

Represents an option in a selection list on an HTML form. For each instance of an HTML <option> tag in a selection list on a form, an Option object is created

OptionContains information about the client browserNavigatorRepresents an HTML meta elementMetaContains information about the current URLLocation

Represents an HTML link element. The link element can only be used within the <head> tag

LinkRepresents an HTML img elementImage

Page 40: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

40

Corresponds to the browser window. A Window object is created automatically with every instance of a <body> or <frameset> tag

Window

Represents an HTML textarea elementTextarea

Represents a text field on an HTML form. For each instance of an HTML <input type="text"> tag on a form, a Text object is created

Text

Represents an HTML tr elementTableRow

Represents an HTML th elementTableHeader

Represents an HTML td elementTableData

Represents an HTML table elementTable

Represents a submit button on an HTML form. For each instance of an HTML <input type="submit"> tag on a form, a Submit object is created

Submit

Represents an individual style statement. This object can be accessed from the document or from the elements to which that style is applied

Style

Page 41: JavaScript - elearning.fesb.unist.hr · 14 Examples • The length property This example returns the number of characters in a string. • The fontcolor() method This example returns

41

• JS DOM Examples