Escolar Documentos
Profissional Documentos
Cultura Documentos
Net Apprentice
JavaScript
O JavaScript uma linguagem de scripting, orientada a objectos e independente de plataformas Criada por Brendan Eich para a NetScape em 1995 Cdigo embebido em paginas HTML Utilizada para:
Interactividade nas pginas HTML Validar formulrios Fazer chamadas assncronas ao servidor - AJAX
Interpretada pelos browsers O verdadeiro nome ECMAScript Desenvolvido e mantido por ECMA organization.
Departamento de Engenharia Informtica ISEP/IPP
.Net Apprentice
<html> <head> </head> <body> <script type="text/javascript"> document.write("This message is written by JavaScript"); </script> </body>
.Net Apprentice
Ficheiro validate.js
function requiredFieldOn(asterisco) { asterisco.style.color="red"; asterisco.style.visibility="visible"; } ..
Departamento de Engenharia Informtica ISEP/IPP
JavaScript
Tipos de dados
Tipos de dados dinmicos
var x= 3.14; var str="hello world";
.Net Apprentice
JavaScript
Variveis
Definio
x = 3.14; var x = 3.14;
Variveis definidas com var e sem valor atribudo tem valor undefined As variveis so globais se definidas fora de uma funo, caso contrrio so variveis locais.
JavaScript
ARRAY
definido como um conjunto de literais
var paises = ["Portugal","Espanha","Frana"];
propriedade length
for (i=0;i<cidades.length;i++) { document.writeln(paises[i]); }
Departamento de Engenharia Informtica ISEP/IPP
.Net Apprentice
JavaScript
Alguns mtodos do objecto Array:
concat- agrupa dois arrays e devolve um novo array join agrupa todos os elementos de um array numa string pop remove o ultimo elemento push acrescenta um elemento sort ordena os elementos do array
JavaScript
Array associativo
Indexao pode ser feita por strings - Keys
var concelho= new Array(); concelho["Porto"] = "Aldoar, Foz, Nevogilde, Lordelo do Ouro"; concelho["Maia"] = "guas Santas, Moreira, Milheir, Vermoim"; concelho["Gaia"] = "Candal, So Pedro da Afurada, Arcozelo"; Document.writeln(concelho["Porto"])
.Net Apprentice
FOR
for ([init];[cond]; [increment]) { statements }
Departamento de Engenharia Informtica ISEP/IPP
.Net Apprentice
JavaScript
Sintaxe OO
objectName.propertyName objectName.methodname(params);
.Net Apprentice
JavaScript
Objecto String
var strmail = new String("jal@dei.isep.ipp.pt")
length
prpriedade que devolve o comprimento de uma string var n=str.length;
indexOf(str1,[start])
mtodo que devolve a posio da primeira ocorrncia de str1 var pos=strmail.indexOf("@");
charAt(index)
mtodo que devolve o caracter da string na posio especificada por index var ch=strmail.charAt(4);
substring(start,end)
mtodo que devolve os caracteres da string entre as posies especificadas
Departamento de Engenharia Informtica ISEP/IPP
JavaScript
Outros mtodos do objecto String
charCodeAt toUpperCase fromCharCode split toLowercase
function leftTrim(sString) { while (sString.substring(0,1) == ' ') { sString = sString.substring(1, sString.length); } return sString.toUpperCase(); }
.Net Apprentice
JavaScript
Objecto Date
construtores
new new new new Date(); // devolve a data do sistema Date( milliseconds) Date( dateString) Date( year, month, day[, hour, minute, second])
mtodos
.getHours(); .getMinutes(); .getDate(); .getMonth(); .getYear(); .getDay() .getTime() .setDate() .setMonth() .setTime() .toString()
JavaScript
Objecto Math
O objecto Math tem mtodos para trabalhar com constantes e funes matemticas
.Net Apprentice
JavaScript
Funes primitivas
parseFloat(str) converte o argumento str num float. Se no for possvel a converso devolve "NaN" (not a number). parseInt(str [, radix]) converte str num inteiro de acordo com o argumento radix. Se no for possvel a converso devolve "NaN" (not a number). isNaN(testValue) devolve true se o argumento um NaN
num = parseInt(document.getElementById(textAno").value); if (isNaN(num) || num > 2015) alert ("erro");
JavaScript Objects
10
.Net Apprentice
JavaScript DOM
window Representa a informao sobre a janela do
browser. Contm a informao sobre as janelas e frames.
navigator Contm informao sobre o browser do utilizador event Contm informao sobre os eventos que ocorrem na
pgina
screen contm informao sobre o ecran do cliente history contm os URLs visitados location contm informao sobre o URL corrente
Departamento de Engenharia Informtica ISEP/IPP
result = window.confirm(text)
apresenta uma janela de dilogo. result um valor booleano com valor true se foi premido o boto OK e false para o boto Cancel
11
.Net Apprentice
window.parent
devolve uma referncia para a janela (frame) pai da janela (frame) corrente.
window.top
devolve uma referncia para a janela principal (ou frameset) numa hierarquia de janelas
windows.setTimeOut
window.setTimeout("tick();", 100); //Funo tick ser chamada ao fim de 100 ms
12
.Net Apprentice
JavaScript - Forms
Cada formulrio HTML num documento cria um objecto form Existe um array forms com os vrios objectos form de um documento. Acesso ao seguinte formulrio em javascript :
<form id="myform" name="myform">
por indice
document.forms[0]
por id/name
document.myform
JavaScript - Forms
getElementByID e getElementsByName
mtodos especificados no DOM-W3C para aceder aos elementos HTML e que so implementados nos browser mais recentes Html
<label>Nome:</label> <input type="text" name="nome" id="idnome" </p>
JavaScript
var nomeInput=document.getElementByID("idnome");
13
.Net Apprentice
JavaScript - Eventos
O JavaScript implementa um modelo de eventos Os eventos permitem escrever cdigo para interagir com as aces do utilizador Para cada evento (click) existe um eventhandler (onclick) para responder ao evento Registo de um evento (onclick) num elemento html (button):
<input type="button" value="Enviar" onClick="validar(this.form)">
Javascript - Eventos
Object
Area Button Checkbox Form Frame Link Select Submit Text Window
Event Handlers
onClick, onMouseOut, onMOuseOver onBlur, onClick, onFocus onBlur, onClick, onFocus onReset, onSubmit onReset, onSubmit onClick, onMouseOut, onMouseOver onBlur, onChange, onFocus onBlur, onClick, onFocus onBlur, onChange, onFocus onBlur, onError, onFocus,onLoad, onUnload
14
.Net Apprentice
JavaScript - EventHandlers
Attribute onabort onblur onchange onclick ondblclick onerror onfocus onkeydown onkeypress onkeyup The event occurs when... Loading of an image is interrupted An element loses focus The user changes the content of a field Mouse clicks an object Mouse double-clicks an object An error occurs when loading a document or an image An element gets focus A keyboard key is pressed A keyboard key is pressed or held down A keyboard key is released
JavaScript - EventHandlers
onload onmousedown onmousemove onmouseout onmouseover onmouseup onreset onresize onselect onsubmit onunload A page or an image is finished loading A mouse button is pressed The mouse is moved The mouse is moved off an element The mouse is moved over an element A mouse button is released The reset button is clicked A window or frame is resized Text is selected The submit button is clicked The user exits the page
15
.Net Apprentice
JavaScript - Eventos
Mouse / Keyboard Attributes
Property altKey button clientX clientY ctrlKey metaKey relatedTarget screenX screenY shiftKey
Departamento de Engenharia Informtica ISEP/IPP
Description Returns whether or not the "ALT" key was pressed when an event was triggered Returns which mouse button was clicked when an event was triggered Returns the horizontal coordinate of the mouse pointer when an event was triggered Returns the vertical coordinate of the mouse pointer when an event was triggered Returns whether or not the "CTRL" key was pressed when an event was triggered Returns whether or not the "meta" key was pressed when an event was triggered Returns the element related to the element that triggered the event Returns the horizontal coordinate of the mouse pointer when an event was triggered Returns the vertical coordinate of the mouse pointer when an event was triggered Returns whether or not the "SHIFT" key was pressed when an event was triggered
http://www.dei.isep.ipp.pt/ARQSI/DHTML/eventosrato.htm
16
.Net Apprentice
Manuel
Departamento de Engenharia Informtica ISEP/IPP
O controlo select tem um array options[ ] A propredade selectedIndex devolve o ndice da opo seleccionada A propriedade text devolve o texto da opo
/* Select sem atributo multiple */ var cidadesElems=document.getElementById("cidades"); index=cidadesElems.selectedIndex; str=cidadesElems.options[index].text;
Departamento de Engenharia Informtica ISEP/IPP
Porto
17
.Net Apprentice
Acesso aos elementos de um Form < input type="radio" >, <input type="checkbox" >,
Regime: <input type="radio" name="Reg" value="D" checked="checked">Diurno <input type="radio" name="Reg" value="N">Nocturno
getElementsByName devolve um array de objectos com o mesmo nome Propriedade checked devolve true se seleccionado Propriedade value devolve o valor do elemento
var radiosElems=document.getElementsByName("Reg"); for (i=0;i<radioElems.length;i++) if (radiosElems[i].checked) str=radiosElems[i].value;
Departamento de Engenharia Informtica ISEP/IPP
18
.Net Apprentice
Deteco do Browser
Deteco do browser do cliente
Objecto navigator do JavaScript Propriedades .appName nome do browser .appVersion verso do browser .platform - plataforma
var browser = navigator.appName; var browserVersion = navigator.appVersion; if (browser=="Microsoft Internet Explorer") ...
browser "Microsoft Internet Explorer" browserVersion 4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET
Departamento de Engenharia Informtica ISEP/IPP
http://www.dei.isep.ipp.pt/ARQSI/DHTML/infoBrowser.html
Deteco do Browser
Detectar browser que implementa a especificao W3C DOM Verificao de propriedades e mtodos implementados
var W3CDOM=(document.getElementsByTagName && document.createElement); if (W3CDOM) { // scripts W3C } else { //scripts adaptados aos browsers mais antigos }
Departamento de Engenharia Informtica ISEP/IPP
19
.Net Apprentice
Expresses Regulares
Usadas para validar a informao num formulrio HTML Criar uma expresso regular:
Com uma expresso literal (usa a sintaxe /padro/):
var regExpr = /^\d{6}$/;
Expresses Regulares
Exemplo
function validate() { var regExpr=/^\d{7}$/; num=document.getElementById("numAluno").value; if (regExpr.test(num)) { return true; } else { alert("Nmero tem de ter 7 dgitos"); return false; } }
Departamento de Engenharia Informtica ISEP/IPP
20
.Net Apprentice
Caracteres especiais
Pattern a digit (positive integer) a non-digit a word character a non-word character a whitespace character a non-whitespace character any single character except newline match one or more occurrences of x Matches the preceding pattern x 0 or 1 times zero or more occurrences of the preceding pattern x
Departamento de Engenharia Informtica ISEP/IPP
Symbol \d \D \w \W \s \S . x+ x? x*
Alternative [0123456789] or [0-9] [^0-9] [a-zA-Z0-9_] [^\w] [ \t\n\r\f] [^\s] [^\n] {1,} {0,}
Caracteres especiais
Pattern Matches at least n and at most m occurrences of the preceding pattern x Matches exactly n occurrences of the preceding pattern x Matches at least n occurrences of the preceding pattern x Anchors your search at the beginning of the line Anchors at the end of the line exactly one character out of the set matches any single character, except a range, i.e. all the characters from char1 to char2 inclusive group or form subpattern & remember or escape special characters
Departamento de Engenharia Informtica ISEP/IPP
Symbol {n,m} x{n} x{n,} ^pattern pattern$ [characters] [^characters] [char1-char2] (sub-pattern) | \
Alternative
21
.Net Apprentice
JavaScript e CSS
Alterao de estilos de um elemento usando o objecto style Sintaxe:
objectElement.style.propriedade=valor
var elemDiv=document.getElementById("p1"); elemDiv.style.color = "black"; elemDiv.style.backGroundColor = "red"; elemDiv.style.display = "block";
22
.Net Apprentice
JavaScript e CSS
Alterao de estilos de um elemento usando a propriedade className Sintaxe:
objectElement.className=nomeClassCss
<script type="text/javascript"> function changeCss() { document.getElementById("myP").className = newStyle; } </script> <style type="text/css"> .newStyle {font: bold 16px verdana;} </style> <p id="myP" onclick="changeCss()">Render this text using the myC class</p>
JavaScript e CSS
Alterao do contedo de um elemento HTML <elemento>.innerHTML
function changeDivOver(iddiv) { var myElem=document.getElementById(iddiv); myElem.style.color="blue"; myElem.style.backgroundColor = "#00DD33; myElem.innerHTML="Departamento de Engenharia Informtica"; }
http://www2.dei.isep.ipp.pt/ades/exemplos_dhtml.html
23
.Net Apprentice
JavaScript - Futuro
O futuro
Web Hypertext Application Technology Working Group http://www.whatwg.org/
HTML 5.0
http://www.whatwg.org/specs/web-apps/current-work/
Novos controlos nos formulrios Validaes e restries declarativas nos controlos - min, max , ... Grficos vectoriais (canvas) linhas, arcos, rectngulos, ..
Departamento de Engenharia Informtica ISEP/IPP
JavaScript - Referncias
Links avanados e divertidos
http://simonbaird.com/coolclock/ http://rainbow.arch.scriptmania.com/scripts/mouse_clock4.html http://www.geekpedia.com/Samples/RTB/Editor.html http://dhtml-menu.com/dhtml-samples/menu375.html http://henrikfalck.com/sudoku/
24