50
Introduc)on to JavaScript Jussi Pohjolainen Tampere University of Applied Sciences

Intro to JavaScript

Embed Size (px)

Citation preview

Page 1: Intro to JavaScript

Introduc)on  to  JavaScript  

Jussi  Pohjolainen  Tampere  University  of  Applied  Sciences  

Page 2: Intro to JavaScript

JavaScript  

•  Object-­‐orientated  scrip)ng  language  •  Dialect  of  EcmaScript-­‐standard  •  History  – Netscape:  LiveScript  to  JavaScript  – MicrosoH:  JScript  – Standard:  EcmaScript  

•  Latest  version:  JavaScript  1.8.1,  a  superset  of  EcmaScript  

Page 3: Intro to JavaScript

Possibili)es?  

•  JS  was  designed  to  add  interac)vity  to  HTML  pages  

•  Dynamic  HTML  •  Can  react  to  events:  page  has  finished  loading,  user  clicks..  

•  Data  valida)on  •  Browser  detec)on  •  Cookies  

Page 4: Intro to JavaScript

Compa)bility  

•  Old  or  rare  browsers  •  PDA  or  Mobile  phones  •  JavaScript  execu)on  disabled  •  The  use  of  speech  browser  •  Browser  incompa)bilites  

Page 5: Intro to JavaScript

JavaScript  Today:  AJAX  

•  JavaScript  is  heavily  used  in  AJAX-­‐based  sites  •  AJAX:  asynchronous  JavaScript  and  XML  – group  of  interrelated  techniques  used  on  the  client-­‐side  to  create  rich  web  apps  where  data  is  retrieved  from  the  server  in  the  background.  

•  Example  usage:  Gmail,  Google  Maps  

Page 6: Intro to JavaScript

Google  Web  Toolkit  

•  Great  tool  for  crea)ng  AJAX/JS-­‐based  sites  •  Coding  is  done  with  Java  which  is  compiled  to  JavaScript  

•  Resolves  browser  incompa)bilies  •  See  Example:  – hZp://gwt.google.com/samples/Showcase/Showcase.html  

Page 7: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Embed Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /

> </head> <body> <p> <!-- See: http://covertprestige.info/html/script-syntax/ --> <script type="text/javascript"> //<![CDATA[ document.write("Hello from JS!"); //]]> </script> </p> </body> </html>

Page 8: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>External JS Example</title>

<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />

<script type="text/javascript" src="event.js"></script>

</head>

<body onload="message()">

</body>

</html>

Page 9: Intro to JavaScript

// event.js

function message()

{

alert("This alert box was called with the onload event");

}

Page 10: Intro to JavaScript

Result  

Page 11: Intro to JavaScript

QUICK  INTRO  TO  PROGRAMMING  WITH  JS  

Page 12: Intro to JavaScript

Variables  

•  Values  are  stored  in  variables  •  Variables  are  declared:  – var carname;

•  Assigning  value  – carname = "volvo";

•  Together  – var carname = "volvo";

Page 13: Intro to JavaScript

... <body> <p> <script type="text/javascript"> //<![CDATA[ // Declaration var car; // Assigning car = "Volvo"; document.write(car); //]]> </script> </p> </body> </html>

Page 14: Intro to JavaScript

Comparison  (w3schools)  <script type="text/javascript"> //<![CDATA[ var d = new Date(); var time = d.getHours(); if ( time < 10 ) {   document.write("<b>Good morning</b>"); } //]]> </script>

Page 15: Intro to JavaScript

Comparison  (w3schools)  <script type="text/javascript">

//<![CDATA[

var d = new Date();

var time = d.getHours();

if ( time < 10 )

{

  document.write("<b>Good morning</b>");

}

else

{

  document.write("<b>Good Day</b>");

}

//]]>

</script>

Page 16: Intro to JavaScript

Repeat  (w3schools)  <script type="text/javascript"> //<![CDATA[ var i=0; while (i<=5) {   document.write("The number is " + i);   document.write("<br />");   i = i + 1; } //]]> </script>

Page 17: Intro to JavaScript

Popup  Boxes  

•  Alert  Box  – alert("some  text");  

•  Confirm  Box  – confirm("some  text");  

•  Prompt  Box  – prompt("sometext",  "default  value")  

Page 18: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-

strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Embed Example</title> <meta http-equiv="content-type" content="application/

xhtml+xml; charset=utf-8" /> </head> <body> <input type="button" onclick="alert('moi');" value="Show

alert box" /> </body> </html>

Page 19: Intro to JavaScript

Result  

Page 20: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Embed Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /

> <script type="text/javascript"> //<![CDATA[ function showAlert() { alert("Hello World!"); } //]]> </script> </head> <body> <input type="button" onclick="showAlert();" value="Show alert box" /> </body> </html>

Page 21: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Embed Example</title> <meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ function askQuestion() { var name = prompt("Please enter your name","Harry Potter"); if ( name!=null && name!="" ) { alert("Hello " + name + "! How are you today?"); } } //]]> </script> </head> <body> <input type="button" onclick="askQuestion();" value="Question for me" /> </body> </html>

Page 22: Intro to JavaScript

JS  EVENTS  AND  DOM  

Page 23: Intro to JavaScript

JS  Events  

•  Mouse  click  (onclick)  •  Web  page  loading  (onload)  •  Mousing  over  and  out  (onmouseover  onmouseout)  

•  Submiang  HTML  form  (onsubmit)    

Page 24: Intro to JavaScript

About  Events  

•  You  may  cancel  some  events:  – <a href=http://www.tamk.fi/ onclick="alert('message'); return false;">

•  Example  – <form name="myform" action="" onsubmit="return validate();">

Page 25: Intro to JavaScript

Example    <form name="myform" method="post" onsubmit="return

count()"> Height (m):<br/> <input type="text" name="height"/><br/> Weight (kg):<br/> <input type="text" name="weight"/><br/> <input type="submit" value="BMI"/><br/> BMI<br/> <input type="text" name="result"/> </form>

Page 26: Intro to JavaScript

<script type="text/javascript">

//<![CDATA[

function count()

{

var height = document.myform.height.value;

var weight = document.myform.weight.value;

document.myform.result.value = (weight / (height*height));

return false;

}

//]]>

</script>

Page 27: Intro to JavaScript

Result  

Page 28: Intro to JavaScript

DOM  

Page 29: Intro to JavaScript

W3C  DOM  

•  DOM  –  Document  Object  Model  –  cross-­‐pladorm  and  language-­‐independent  conven)on  for  interac)ng  with  objects  in  HTML  and  in  XML.  

•  With  DOM  you  can  manipulate  html/xml  document!  Dynamic  html!  

•  Public  interface  available:  hZp://www.w3.org/DOM/DOMTR    

Page 30: Intro to JavaScript

W3C  DOM  Levels  

•  (  DOM  Level  0  and  Intermediate  DOM  )  – Not  W3C  Standards,  used  in  Netscape  2  (Level  0)  and  Netscape  4  (Intermediate  DOM)    

•  DOM  Level  1  –  1998:  Ability  to  change  en)re  HTML  or  XML  document  

•  DOM  Level  2  –  2001:  Introduces  “getElementById”  func)on,  event  model  and  support  for  XML  namespaces  

•  DOM  Level  3  –  2004:  XPath,  keyboard  event  handling  

Page 31: Intro to JavaScript

Reality  

Page 32: Intro to JavaScript

Node  

•  In  DOM,  each  object  is  Node  •  In  this  – <p>Hello</p>  

•  You  have  two  nodes  1)  element  node  p  2)  text  node  Hello  

•  Text  node  is  child  node  of  p  element.  P  element  is  parent  node  of  the  text  node  

Page 33: Intro to JavaScript

Node  Example  <p>This is a <strong>paragraph</strong></p> <p> | -------------- | | This is a <strong> | | paragraph

Page 34: Intro to JavaScript

AZribute  Node  

<a href=“http://www.tamk.fi”>TAMK</a> <a> ----------------- | | TAMK href | http://www.tamk.fi

Page 35: Intro to JavaScript

Nodes  

•  Element  node:  p,  img,  a  •  Text  node:  sometext  •  AZribute  node:  src  

Page 36: Intro to JavaScript

DOM  Level  1:  To  Access  DOM  tree  

•  X  can  be  some  node  – var  parent  =  x.parentNode;  – var  firstchild  =  x.childNodes[0];  

•  How  to  get  reference  to  x?  

Page 37: Intro to JavaScript

window  -­‐  object  

•  Every  reference  to  other  objects  is  done  via  the  window  –  object  

•  You  don't  have  to  use  the  reference  in  your  code:  – window.document.form.height.value  =  – document.form.height.value  

•  Window  methods  – alert,  close,  confirm,  open,  prompt,  setTimeOut  

Page 38: Intro to JavaScript

Document  object  

Page 39: Intro to JavaScript

Access  

var title = document.firstChild.firstChild.lastChild;

// document.html.head.title

var title = document.firstChild.childNodes[0].childNodes[0];

Page 40: Intro to JavaScript

Geang  Element  Easier  Way  

var x = document.getElementsByTagName(‘strong')[0]

var x = document.getElementById('hereweare');

 

Page 41: Intro to JavaScript

Changing  the  Node  

// <a href=“” id=“someId”>Link</p>

var x = document.getElementById(’someId');

x.firstChild.nodeValue = “Hello!”;

x.setAttribute(“href”, “http:/…”);

 

Page 42: Intro to JavaScript

Inner  HTML  

// <a href=“” id=“someId”>Link</p>

var x = document.getElementById(’someId');

x.innerHTML = “Hello!”;

 //  innerHTML  is  NOT  W3C  Standard  and  it’s  //  slower…  

Page 43: Intro to JavaScript

Crea)ng  and  Removing  Nodes  var x = document.createElement(’hr');

document.getElementById('inserthrhere').appendChild(x);

var node = document.getElementById('inserthrhere')

node.removeChild(node.childNodes[0]);

var x = document.createTextNode(’SomeText');

document.getElementById('hereweare').appendChild(x);

Page 44: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />

<script type="text/javascript">

//<![CDATA[

function change()

{

// Get list of ALL <h1> - elements

var listOfHeading1 = window.document.getElementsByTagName("h1");

// Find the first <h1> - element in the list

var heading1 = listOfHeading1[0];

// Get the child - element of the first <h1> - element (Text)

var text = heading1.firstChild;

// Replace the text

text.data = "Hello from JS!";

}

//]]>

</script>

</head>

<body>

<h1>Title</h1>

<input type="submit" onClick="change();" value="click!"/>

</body>

</html>

Page 45: Intro to JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title></title>

<meta http-equiv="content-type" content="application/xhtml+xml; charset=utf-8" />

<script type="text/javascript">

//<![CDATA[

function change()

{

// Reference to the table - element

var table = document.getElementById("mytable");

var tr = document.createElement("tr"); // <tr>

var td1 = document.createElement("td"); // <td>

var td1Text = document.createTextNode("New Cell"); // "New Cell"

td1.appendChild(td1Text); // <td>New Cell</td>

var td2 = document.createElement("td"); // <td>

var td2Text = document.createTextNode("New Cell"); // "New Cell"

td2.appendChild(td2Text); // <td>New Cell</td>

tr.appendChild(td1);

tr.appendChild(td2);

table.appendChild(tr);

}

//]]>

</script>

</head>

<body>

<table id="mytable" border="1">

<tr><td>&nbsp;</td><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td><td>&nbsp;</td></tr>

<tr><td>&nbsp;</td><td>&nbsp;</td></tr>

</table>

<input type="submit" onClick="change();" value="Add Row"/>

</body>

</html>

Page 46: Intro to JavaScript

DOM  Level  0  

•  DOM  Level  1  supports  also  Level  0  •  Level  0:  Only  access  to  elements  •  Browsers  will  con)nue  to  support  it  •  Access  elements  by  name:  – <img  name=“myimage”  src=“..”/>  – document.images[’myimage'].src  =  'another_image.gif';  

 

Page 47: Intro to JavaScript

DOM  Objects  

Page 48: Intro to JavaScript

Accessing  Forms  in  DOM  0  document.forms[’myform'].elements['address']

document.forms['myform'].elements[0]

document.forms[0].elements['address’]

document.forms[0].elements[0]

Page 49: Intro to JavaScript

Opening  new  Browser  Window  

// See: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

window.open("http://www.tamk.fi",

"title",

"width=600, height=100");

 

Page 50: Intro to JavaScript

navigator  -­‐  object  

•  navigator  tells  informa)on  about  your  browser  

•  Client-­‐sniffing  var browser = navigator.appName; var b_version = navigator.appVersion; var version = parseFloat(b_version); document.write("Browser name: "+ browser); document.write("<br />"); document.write("Browser version: "+ version);