SlideShare a Scribd company logo
1 of 50
Download to read offline
Introduc)on	
  to	
  JavaScript	
  

            Jussi	
  Pohjolainen	
  
Tampere	
  University	
  of	
  Applied	
  Sciences	
  
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	
  
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	
  
Compa)bility	
  
•    Old	
  or	
  rare	
  browsers	
  
•    PDA	
  or	
  Mobile	
  phones	
  
•    JavaScript	
  execu)on	
  disabled	
  
•    The	
  use	
  of	
  speech	
  browser	
  
•    Browser	
  incompa)bilites	
  
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	
  
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	
  
<!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>
<!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>
// event.js
function message()
{
    alert("This alert box was called
  with the onload event");
}
Result	
  
QUICK	
  INTRO	
  TO	
  PROGRAMMING	
  
WITH	
  JS	
  
Variables	
  
•  Values	
  are	
  stored	
  in	
  variables	
  
•  Variables	
  are	
  declared:	
  
    –  var carname;
•  Assigning	
  value	
  
    –  carname = "volvo";
•  Together	
  
    –  var carname = "volvo";
...
<body>

<p>
<script type="text/javascript">
//<![CDATA[

// Declaration
var car;
// Assigning
car = "Volvo";
document.write(car);

//]]>
</script>
</p>

</body>
</html>
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>
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>
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>
Popup	
  Boxes	
  
•  Alert	
  Box	
  
    –  alert("some	
  text");	
  
•  Confirm	
  Box	
  
    –  confirm("some	
  text");	
  
•  Prompt	
  Box	
  
    –  prompt("sometext",	
  "default	
  value")	
  
<!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>
Result	
  
<!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>
<!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>
JS	
  EVENTS	
  AND	
  DOM	
  
JS	
  Events	
  
•  Mouse	
  click	
  (onclick)	
  
•  Web	
  page	
  loading	
  (onload)	
  
•  Mousing	
  over	
  and	
  out	
  (onmouseover	
  
     onmouseout)	
  
•  Submiang	
  HTML	
  form	
  (onsubmit)	
  
	
  
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();">
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>
<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>
Result	
  
DOM	
  
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	
  	
  
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	
  
Reality	
  
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	
  
Node	
  Example	
  
<p>This is a <strong>paragraph</strong></p>


              <p>
               |
         --------------
        |              |
    This is a       <strong>
                       |
                       |
                    paragraph
AZribute	
  Node	
  
<a href=“http://www.tamk.fi”>TAMK</a>


          <a> -----------------
           |                    |
         TAMK                href
                                |
                       http://www.tamk.fi
Nodes	
  
•  Element	
  node:	
  p,	
  img,	
  a	
  
•  Text	
  node:	
  sometext	
  
•  AZribute	
  node:	
  src	
  
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?	
  
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	
  
Document	
  object	
  
Access	
  
var title =
document.firstChild.firstChild.lastChild;
// document.html.head.title

var title =
document.firstChild.childNodes[0].childNodes[
0];
Geang	
  Element	
  Easier	
  Way	
  
var x =
document.getElementsByTagName(‘strong')[0]

var x = document.getElementById('hereweare');
	
  
Changing	
  the	
  Node	
  
// <a href=“” id=“someId”>Link</p>
var x =
document.getElementById(’someId');
x.firstChild.nodeValue = “Hello!”;
x.setAttribute(“href”, “http:/…”);
	
  
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…	
  
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);
<!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>
<!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>
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';	
  
      	
  
DOM	
  Objects	
  
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]
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");
	
  
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);

More Related Content

What's hot

JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & eventBorey Lim
 
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...kiphampton
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
CSS pattern libraries
CSS pattern librariesCSS pattern libraries
CSS pattern librariesRuss Weakley
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsAdrien Guéret
 
Javascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsNet7
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Railsdosire
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajaxSynapseindiappsdevelopment
 
Killing the Angle Bracket
Killing the Angle BracketKilling the Angle Bracket
Killing the Angle Bracketjnewmanux
 
Zen codingcheatsheet
Zen codingcheatsheetZen codingcheatsheet
Zen codingcheatsheetgoldenveizer
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application developmentzonathen
 

What's hot (20)

JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
 
Intro to Web Standards
Intro to Web StandardsIntro to Web Standards
Intro to Web Standards
 
lect9
lect9lect9
lect9
 
Ws rest
Ws restWs rest
Ws rest
 
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
Stop Making The Web Harder Than It Is; Real-world REST, HATEOAS, and Hypermed...
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Introduction to Html5
Introduction to Html5Introduction to Html5
Introduction to Html5
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
CSS pattern libraries
CSS pattern librariesCSS pattern libraries
CSS pattern libraries
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.js
 
Javascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basics
 
When To Use Ruby On Rails
When To Use Ruby On RailsWhen To Use Ruby On Rails
When To Use Ruby On Rails
 
Synapseindia dot net development web applications with ajax
Synapseindia dot net development  web applications with ajaxSynapseindia dot net development  web applications with ajax
Synapseindia dot net development web applications with ajax
 
AJAX - An introduction
AJAX - An introductionAJAX - An introduction
AJAX - An introduction
 
Killing the Angle Bracket
Killing the Angle BracketKilling the Angle Bracket
Killing the Angle Bracket
 
HTML5 - An introduction
HTML5 - An introductionHTML5 - An introduction
HTML5 - An introduction
 
Advanced Json
Advanced JsonAdvanced Json
Advanced Json
 
Zen codingcheatsheet
Zen codingcheatsheetZen codingcheatsheet
Zen codingcheatsheet
 
Intro to mobile web application development
Intro to mobile web application developmentIntro to mobile web application development
Intro to mobile web application development
 

Viewers also liked

Java topology abstraction service for ip-vp ns
Java  topology abstraction service for ip-vp nsJava  topology abstraction service for ip-vp ns
Java topology abstraction service for ip-vp nsecwayerode
 
IoT and META-engineering with Service Templates
IoT and META-engineering with Service TemplatesIoT and META-engineering with Service Templates
IoT and META-engineering with Service TemplatesHans A. Kielland Aanesen
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstractionRaghav Chhabra
 
AR+S The Role Of Abstraction In Human Computer Interaction
AR+S   The Role Of Abstraction In Human Computer InteractionAR+S   The Role Of Abstraction In Human Computer Interaction
AR+S The Role Of Abstraction In Human Computer InteractionAli Rıza SARAL
 
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody. Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody. Sarah Ju-En Tan
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classesAnup Burange
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionPritom Chaki
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52myrajendra
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaAdil Mehmoood
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous classHarry Potter
 

Viewers also liked (20)

Java topology abstraction service for ip-vp ns
Java  topology abstraction service for ip-vp nsJava  topology abstraction service for ip-vp ns
Java topology abstraction service for ip-vp ns
 
IoT and META-engineering with Service Templates
IoT and META-engineering with Service TemplatesIoT and META-engineering with Service Templates
IoT and META-engineering with Service Templates
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Java JDBC
Java JDBCJava JDBC
Java JDBC
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstraction
 
File class.48
File class.48File class.48
File class.48
 
IEEE DEST CEE 2013 - Paper 4 (1) (1)
IEEE DEST CEE 2013 - Paper 4 (1) (1)IEEE DEST CEE 2013 - Paper 4 (1) (1)
IEEE DEST CEE 2013 - Paper 4 (1) (1)
 
AR+S The Role Of Abstraction In Human Computer Interaction
AR+S   The Role Of Abstraction In Human Computer InteractionAR+S   The Role Of Abstraction In Human Computer Interaction
AR+S The Role Of Abstraction In Human Computer Interaction
 
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody. Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
Final Animation Assessment Presentation: The Abstraction of Bohemian Rhapsody.
 
Java stereams
Java stereamsJava stereams
Java stereams
 
Java lecture
Java lectureJava lecture
Java lecture
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Object Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaionObject Oriented Programing JAVA presentaion
Object Oriented Programing JAVA presentaion
 
Character stream classes .52
Character stream classes .52Character stream classes .52
Character stream classes .52
 
Inner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in javaInner classes ,annoumous and outer classes in java
Inner classes ,annoumous and outer classes in java
 
PAC
PACPAC
PAC
 
Java Inner Classes
Java Inner ClassesJava Inner Classes
Java Inner Classes
 
Encapsulation anonymous class
Encapsulation anonymous classEncapsulation anonymous class
Encapsulation anonymous class
 
Abstract class
Abstract classAbstract class
Abstract class
 
Operators in java
Operators in javaOperators in java
Operators in java
 

Similar to Intro to JavaScript

Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
Introduction to Web Standards
Introduction to Web StandardsIntroduction to Web Standards
Introduction to Web StandardsJussi Pohjolainen
 
Html5 and web technology update
Html5 and web technology updateHtml5 and web technology update
Html5 and web technology updateDoug Domeny
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Asher Martin
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Hugo Hamon
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen LjuSkills Matter
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen LjuSkills Matter
 
Building native mobile apps using web technologies
Building native mobile apps using web technologiesBuilding native mobile apps using web technologies
Building native mobile apps using web technologiesHjörtur Hilmarsson
 
`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew Ivasiv`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew IvasivLemberg Solutions
 

Similar to Intro to JavaScript (20)

Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
HTML 5 - Overview
HTML 5 - OverviewHTML 5 - Overview
HTML 5 - Overview
 
lect9
lect9lect9
lect9
 
Introduccion a HTML5
Introduccion a HTML5Introduccion a HTML5
Introduccion a HTML5
 
html5
html5html5
html5
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Introduction to Web Standards
Introduction to Web StandardsIntroduction to Web Standards
Introduction to Web Standards
 
JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Html5 and web technology update
Html5 and web technology updateHtml5 and web technology update
Html5 and web technology update
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2Build powerfull and smart web applications with Symfony2
Build powerfull and smart web applications with Symfony2
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 
Primefaces Nextgen Lju
Primefaces Nextgen LjuPrimefaces Nextgen Lju
Primefaces Nextgen Lju
 
T5 Oli Aro
T5 Oli AroT5 Oli Aro
T5 Oli Aro
 
Jquery fundamentals
Jquery fundamentalsJquery fundamentals
Jquery fundamentals
 
Building native mobile apps using web technologies
Building native mobile apps using web technologiesBuilding native mobile apps using web technologies
Building native mobile apps using web technologies
 
`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew Ivasiv`From Prototype to Drupal` by Andrew Ivasiv
`From Prototype to Drupal` by Andrew Ivasiv
 
Camel as a_glue
Camel as a_glueCamel as a_glue
Camel as a_glue
 

More from Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformJussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 
Intro to Java ME and Asha Platform
Intro to Java ME and Asha PlatformIntro to Java ME and Asha Platform
Intro to Java ME and Asha Platform
 

Recently uploaded

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

Intro to JavaScript

  • 1. Introduc)on  to  JavaScript   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. 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  
  • 3. 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  
  • 4. Compa)bility   •  Old  or  rare  browsers   •  PDA  or  Mobile  phones   •  JavaScript  execu)on  disabled   •  The  use  of  speech  browser   •  Browser  incompa)bilites  
  • 5. 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  
  • 6. 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  
  • 7. <!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>
  • 8. <!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>
  • 9. // event.js function message() { alert("This alert box was called with the onload event"); }
  • 11. QUICK  INTRO  TO  PROGRAMMING   WITH  JS  
  • 12. Variables   •  Values  are  stored  in  variables   •  Variables  are  declared:   –  var carname; •  Assigning  value   –  carname = "volvo"; •  Together   –  var carname = "volvo";
  • 13. ... <body> <p> <script type="text/javascript"> //<![CDATA[ // Declaration var car; // Assigning car = "Volvo"; document.write(car); //]]> </script> </p> </body> </html>
  • 14. 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>
  • 15. 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>
  • 16. 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>
  • 17. Popup  Boxes   •  Alert  Box   –  alert("some  text");   •  Confirm  Box   –  confirm("some  text");   •  Prompt  Box   –  prompt("sometext",  "default  value")  
  • 18. <!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>
  • 20. <!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>
  • 21. <!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>
  • 22. JS  EVENTS  AND  DOM  
  • 23. JS  Events   •  Mouse  click  (onclick)   •  Web  page  loading  (onload)   •  Mousing  over  and  out  (onmouseover   onmouseout)   •  Submiang  HTML  form  (onsubmit)    
  • 24. 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();">
  • 25. 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>
  • 26. <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>
  • 29. 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    
  • 30. 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  
  • 32. 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  
  • 33. Node  Example   <p>This is a <strong>paragraph</strong></p> <p> | -------------- | | This is a <strong> | | paragraph
  • 34. AZribute  Node   <a href=“http://www.tamk.fi”>TAMK</a> <a> ----------------- | | TAMK href | http://www.tamk.fi
  • 35. Nodes   •  Element  node:  p,  img,  a   •  Text  node:  sometext   •  AZribute  node:  src  
  • 36. 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?  
  • 37. 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  
  • 39. Access   var title = document.firstChild.firstChild.lastChild; // document.html.head.title var title = document.firstChild.childNodes[0].childNodes[ 0];
  • 40. Geang  Element  Easier  Way   var x = document.getElementsByTagName(‘strong')[0] var x = document.getElementById('hereweare');  
  • 41. Changing  the  Node   // <a href=“” id=“someId”>Link</p> var x = document.getElementById(’someId'); x.firstChild.nodeValue = “Hello!”; x.setAttribute(“href”, “http:/…”);  
  • 42. 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…  
  • 43. 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);
  • 44. <!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>
  • 45. <!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>
  • 46. 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';    
  • 48. 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]
  • 49. 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");  
  • 50. 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);