Você está na página 1de 17

smaranda.belciug@inf.ucv.

ro Laborator 8 Tehnologii Web si Programare Client Server

Funcii O funcie este un set de instruciuni JavaScript grupate, care: se identific printr-un nume este separat de restul script-ului execut un task specific trebuie apelat de alte pri din script pentru a putea fi executat O funcie const n: declararea funciei, care conine cuvntul cheie function, un nume unic de funcie i paranteze. Se mai pot aduga valori n funcie, adugnd argumente ntre paranteze. Blocul funciei.

smaranda.belciug@inf.ucv.ro Structura de baz a unei funcii arat aa:


function name_of_function(argument) { // instruciuni } function alertMessage() { alert(Please enter a value in this field.) }

Cnd pagina se ncarc n browser i script-ul este procesat de browser, codul funciei nu ruleaz automat. El trebuie s fie apelat n script.
<!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> <title>Function calling</title> <script language=javascript type=text/javascript> function saySomething(message) { alert(message) } </script> </head> <body> <h2>Famous Quotes</h2> <hr /> <form action=#> <input type=button value=George Orwell onclick= saySomething(To write or even speak English is not a science but an art.) /> <input type=button value=Arthur Conan Doyle onclick= saySomething(We cannot command our love, but we can our actions.) /> <input type=button value=H.G. Wells onclick= saySomething(If we do not end war, war will end us.) /> </form> </body> </html>

smaranda.belciug@inf.ucv.ro

Array-uri Un array este o colecie de valori. Array-urile sunt folositoare deoarece le putem folosi pentru a manipula i sorta grupuri de obiecte. Locaia informaiei ntr-un array este bazat pe un numr, numit index. Index-ul ncepe de la 0. JavaScript are un obiect special obiectul Array - care lucreaz cu array-uri. Crearea unui array
x = new Array()

Poi s introduci elemente n array, n momentul n care-l creezi:


theDays = new Array(Monday, Tuesday, Wednesday, Thursday, Friday,Saturday, Sunday)

Accesarea array-urilor Dup ce un array a fost creat, pot s scrii sau s citeti din el, folosind operatorul []. Plasnd un numr n acest operator, poi s accesezi dat stocat la acel numr. Citirea elementelor Pentru a citi un element dintr-un array, se creeaz o variabil i se asigneaz ei o valoare din array, astfel:
thisDay = theDays[6]

Valoarea variabilei thisDay este Sunday.

smaranda.belciug@inf.ucv.ro

Scrierea elementelor: Pentru a scrie o valoare n array se procedeaz astfel: 1. Se identific indexul valorii pe care dorim s o schimbm 2. Se asigneaz o nou valoare acestui element, astfel:
theDays[0] = Mon

Looping Fiecare array are o proprietate numit lungime, care este foarte folositoare pentru a descoperi cte elemente conine array-ul i se folosete astfel:
planets = new Array (Mercury, Venus, Earth, Mars) for (i = 0; i < planets.length; i++) alert (planets[i]);

Obiecte Majoritatea script-urilor JavaScript sunt fcute s dea viaa unor obiecte care exist nuntrul browser-ului. Un rollover aduce la via o imagine, se pot valida cmpurile adreselor de e-mail etc. n JavaScript, lucrezi cu o varietate de obiecte cum ar fi o fereastr de browser, un button, un cmp dintr-un formular, o imagine sau chiar documentul nsui. Deci, JavaScript este un limbaj bazat pe obiecte. JavaScript folosete punctul pentru a accesa proprietile unui obiect sau metodele sale:
object.property object.method()

De exemplu, pentru a obine titlul unui document i atribuirea lui unei variabile, se scrie:
mytitle = document.title

Pentru a apela metoda clear a documentului, se scrie:


document.clear()

Evenimente i lucrul cu evenimente Event handler


onabort onblur

Descriere Utilizatorul oprete ncrcarea unei pagini Un element nu mai este n planul principal, utilizatorul orientndu-se ctre un altul 4

smaranda.belciug@inf.ucv.ro
onchange onclick ondblclick onerror onfocus onkeydown onkeyup onload onmousedown onmousemove onmouseout onmouseover onmouseup onreset onresize onselect onsubmit onunload

Utilizatorul schimb coninutul unui formular, selecteaz un buton radio, un checkbox etc. Utilizatorul face click pe element Utilizatorul face dublu-click pe element Browser-ul ntlnete o eroare n script sau n pagin Un element capteaz atenia utilizatorului (un formular care trebuie completat) Utilizatorul ine apsat o tast Utilizatorul d drumul unei taste Browser-ul ncarc o pagin HTML Utilizatoul ine apsat butonul mouse-ului deasupra unui element Utilizatorul mica mouse-ul prin pagin Utilizatoul mut mouse-ul de pe un element Utilizatorul mut mouse-ul peste un element Utilizatorul d drumul la butonul mouse-ului Utilizatorul d click pe butonul Reset al unui formular Utilizatorul redimensioneaz fereastra browser-ului Utilizatorul selecteaz un buton, un meniu etc. Utilizatorul d click pe butonul Submit al unui formular Browser-ul nceteaz ncrcarea unei pagini, deoarece se pregtete s ncarce o alta

<form onsubmit=submitIt(this) action=submitForm.cgi> <input type=button value=Click Me! name=button1 onclick=alert(That tickles!); /> document.button1.onclick = function () { alert(That tickles!)}

smaranda.belciug@inf.ucv.ro

Dynamic HTML Dynamic HTML, aka DHTML, reprezint o combinaie ntre HTML, CSS, Document Object Model (DOM) i JavaScript. Adugarea rollover-urilor n pagin Rollover-ul este elevul cel mai popular din coala JavaScript. Fr el, butoanele par plictisitoare. Vizitatorii s-ar putea nici mcar s nu-i dea seama c pe pagina ta sunt butoane! Se poate folosi un generator de butoane (gratis!!!) la www.tomaweb.com/buttons.asp pentru a crea butoanele din acest laborator! S considerm cele dou imagini ale aceluiai buton: n partea stng avem de a face cu butonul inactiv. n dreapta, este prezentat modul n care arat butonul cnd cursorul mouseului este trecut peste el. Statea activ.

<!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> <title>JavaScript Image Rollover</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <script type=text/javascript language=javascript> function chgImg(imgField,imgState) { document[imgField].src = images/ + imgField + imgState } </script> </head> <body> <a href=index.html onmouseover=chgImg(homeButton,On) onmouseout=chgImg(homeButton,Off)> <img src=images/homeButtonOff.gif width=65 height=15 border=0 alt=Go Home name=homeButton /></a> </body> </html>

+ .gif

smaranda.belciug@inf.ucv.ro
<!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> <title>JavaScript Image Rollover</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <script type=text/javascript language=javascript> //Preloads images if (document.images) { homeButtonOn = new Image homeButtonOff = new Image homeButtonOn.src = homeButtonOn.gif homeButtonOff.src = homeButtonOff.gif } function chgImg(imgField,imgState) { document[imgField].src = imgField + imgState + .gif } </script> </head> <body> <a href=index.html onmouseover=chgImg(homeButton,On) onmouseout=chgImg(homeButton,Off)> <img src=homeButtonOff.gif width=80 height=30 border=0 alt=Go Home name=homeButton /></a> </body> </html>

Text rollover-uri cu CSS

<!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> <title>CSS Text Rollover</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <style type=text/css>

smaranda.belciug@inf.ucv.ro
h4 {font: 18px geneva, sans-serif; margin: 0; color: #000; background: #FFF;} a {text-decoration: none;} div#navbar {width: 100px;} div#navbar a {display:block; margin: 0; padding: 0.3em;} div#navbar a:link {color: #008080; background-color: div#navbar a:visited {color: #C0C0C0; background-color: div#navbar a:hover {background: #FFFFFF; color: #008080;} </style> </head> <body> <div id=navbar> <h4><a href=index.html>Home</a></h4> <h4><a href=aboutMe.html>About Me</a></h4> </div> </body> </html>

transparent;} transparent;}

HTML i JavaScript

<!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> <title>HTML Clock</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <script type=text/javascript language=javascript> window.onload = theClock function theClock() { now = new Date; theTime = ((now.getHours() > 0 && now.getHours() < 13)) ? now.getHours() : (now.getHours() == 0) ? 12 : now.getHours()-12; theTime += (now.getMinutes() > 9) ? : + :0 + now.getMinutes(); theTime += (now.getSeconds() > 9) ? : + :0 + now.getSeconds(); theTime += (now.getHours() < 12) ? am : pm; now.getSeconds() :

now.getMinutes() :

smaranda.belciug@inf.ucv.ro
document.myForm.myClock.value = theTime; setTimeout(theClock(),1000); } </script> </head> <body> <form action=# name=myForm> The current time is <input type=text name=myClock readonly=readonly size=11 /> </form> </body> </html>

<!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> <title>DOM-based Clock</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <script type=text/javascript language=javascript1.5> window.onload = theClock function theClock() { now = new Date; theTime = ((now.getHours() > 0 && now.getHours() < 13)) ? now.getHours() : (now.getHours() == 0) ? 12 : now.getHours()-12; theTime += (now.getMinutes() > 9) ? : + now.getMinutes() : :0 + now.getMinutes(); theTime += (now.getSeconds() > 9) ? : + now.getSeconds() : :0 + now.getSeconds(); theTime += (now.getHours() < 12) ? am : pm; clockSpan = document.getElementById(myClock); clockSpan.replaceChild(document.createTextNode(theTime), clockSpan.firstChild); setTimeout(theClock(),1000); } </script> </head> <body> The current time is <span id=myClock>?</span> </body> </html>

smaranda.belciug@inf.ucv.ro

Pop-up windows

<!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> <title>Window opener</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <script type=text/javascript language=javascript> function OpenWindow (newPage) { window.open(newPage,newWin,width=200,height=50,resizable=yes); } </script> </head> <body> <a href=domClock.html onclick=OpenWindow(this.href);return false>Open a new clock</a> </body> </html>

Lucrul cu cookie-urile

10

smaranda.belciug@inf.ucv.ro

<!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> <title>Cookie Demo</title> <meta http-equiv=Content-Type content=text/html; charset=ISO-8859-1 /> <script type=text/javascript language=javascript> now = new Date expireDate = new Date expireDate.setMonth(expireDate.getMonth()+6) hitCt = parseInt(cookieVal(pageHit)) hitCt++ lastVisit = cookieVal(pageVisit) if (lastVisit == 0) { lastVisit = } document.cookie = pageHit=+hitCt+;expires= + expireDate.toGMTString() document.cookie = pageVisit=+now+;expires= + expireDate.toGMTString() function cookieVal(cookieName) { thisCookie = document.cookie.split(; ) for (i=0; i<thisCookie.length; i++) { if (cookieName == thisCookie[i].split(=)[0]) { return thisCookie[i].split(=)[1] } } return 0 } </script> </head> <body> <h2> <script type=text/javascript language=javascript> document.write(You have visited this page + hitCt + times.) if (lastVisit != ) { document.write(<br />Your last visit was + lastVisit) } </script> </h2> </body> </html>

Exemple. 1. Un simplu roll-over.

11

smaranda.belciug@inf.ucv.ro

Listing script01.css body { background-color: #FFF; } img { border-width: 0; } img#arrow, img#arrowImg { width: 147px; height: 82px; } #button1, #button2 { width: 113px; height: 33px; } .centered { text-align: center; } #adBanner { width: 400px; height: 75px; } Listing script01.html <!DOCTYPE html> <html> <head> <title>A Simple Rollover</title> <link rel="stylesheet" href="script01.css"> </head> <body> 12

smaranda.belciug@inf.ucv.ro <a href="next.html" onmouseover="document.images['arrow'].src='images/arrow_on.gif'" onmouseout="document.images['arrow'].src='images/arrow_off.gif'"><img src="images/arrow_off.gif" id="arrow" alt="arrow"></a> </body> </html> 2.

13

smaranda.belciug@inf.ucv.ro

Listing script02.js window.onload = initLinks; var myPix = new Array("images/robot1.jpg","images/robot2.jpg","images/robot3.jpg"); var thisPic = 0; function initLinks() { document.getElementById("prevLink").onclick = processPrevious; document.getElementById("nextLink").onclick = processNext; } function processPrevious() { if (thisPic == 0) { thisPic = myPix.length; } thisPic--; document.getElementById("myPicture").src = myPix[thisPic]; return false; } function processNext() { thisPic++; if (thisPic == myPix.length) { thisPic = 0; } document.getElementById("myPicture").src = myPix[thisPic]; 14

smaranda.belciug@inf.ucv.ro return false; } Listing script02.js <!DOCTYPE html> <html> <head> <title>Image Slideshow</title> <script src="script02.js"></script> <link rel="stylesheet" href="script01.css"> </head> <body> <div class="centered"> <h1>Welcome, Robot Overlords!</h1> <img src="images/robot1.jpg" id="myPicture" width="200" height="400" alt="Slideshow"> <h2><a href="previous.html" id="prevLink">&lt;&lt; Previous</a>&nbsp;&nbsp;<a href="next.html" id="nextLink">Next &gt;&gt;</a></h2> </div> </body> </html> 3.

15

smaranda.belciug@inf.ucv.ro

Listing script03.js window.onload = choosePic; var adImages = new Array("images/reading1.gif","images/reading2.gif","images/reading3.gif"); var thisAd = 0; function choosePic() { thisAd = Math.floor((Math.random() * adImages.length)); document.getElementById("adBanner").src = adImages[thisAd]; rotate(); } function rotate() { thisAd++; if (thisAd == adImages.length) { thisAd = 0; } document.getElementById("adBanner").src = adImages[thisAd]; setTimeout(rotate, 3 * 1000); } <!DOCTYPE html> <html> <head> <title>Rotating Random Banner</title> <script src="script03.js"></script> <link rel="stylesheet" href="script01.css"> </head> <body> <div class="centered"> <img src="images/spacer.gif" id="adBanner" alt="Ad Banner"> 16

smaranda.belciug@inf.ucv.ro </div> </body> </html>

17

Você também pode gostar