SlideShare uma empresa Scribd logo
1 de 43
Introduction to
        JavaScript Development
                           The Magic of Dynamic Web Pages


Doncho Minkov
Technical Trainer
http://minkov.it
Telerik Software Academy
academy.telerik.com
Table of Contents
   Dynamic HTML
   How to Create DHTML?
     XHTML, CSS, JavaScript, DOM
   Intro to JavaScript
     History
     JavaScript in Web Pages
    JavaScript Syntax
   Pop-up boxes
    Debugging in JavaScript
                                               2
Dynamic HTML
Dynamic Behavior at the Client Side
What is DHTML?
 Dynamic HTML (DHTML)

  Makes possible a Web page to react and change
   in response to the user’s actions
 DHTML consists of HTML   + CSS + JavaScript

                    DHTML

  XHTML       CSS      JavaScript     DOM

                                                   4
DTHML = HTML + CSS + JavaScript
 HTML defines Web sitescontent through
 semantic tags (headings, paragraphs, lists, …)
 CSS defines 'rules'
                    or 'styles' for presenting
 every aspect of an HTML document
   Font (family, size, color, weight, etc.)
   Background (color, image, position, repeat)
   Position and layout (of any object on the page)
 JavaScript   defines dynamic behavior
   Programming logic for interaction with the
    user, to handle events, etc.
                                                      5
JavaScript
Dynamic Behavior in a Web Page
JavaScript
 JavaScript
           is a front-end scripting language
 developed by Netscape for dynamic content
   Lightweight, but with limited capabilities
   Can be used as object-oriented language
   Embedded in your HTML page
   Interpreted by the Web browser
 Client-side, mobile and desktop technology

 Simple and flexible

 Powerful to manipulate the DOM
                                                   7
JavaScript Advantages
 JavaScript   allows interactivity such as:
   Implementing form validation
   React to user actions, e.g. handle keys
   Changing an image on moving mouse over it
   Sections of a page appearing and disappearing
   Content loading and changing dynamically
   Performing complex calculations
   Custom HTML controls, e.g. scrollable table
   Implementing AJAX functionality
                                                    8
What Can JavaScript Do?
 Can handle events

 Can read and write HTML elements and
 modify the DOM tree
 Can validate   form data
 Can access / modify browser cookies

 Can detect the user’s   browser and OS
 Can be used as object-oriented language

 Can handle exceptions

 Can perform asynchronous     server calls (AJAX)
                                                     9
The First Script

<html>

<body>
  <script type="text/javascript">
     alert('Hello JavaScript!');
  </script>
</body>

</html>




                                                 10
First JavaScript
    Live Demo
Using JavaScript Code
 The JavaScript   code can be placed in:
   <script> tag in the head
   <script> tag in the body - not recommended
   External files, linked via <script> tag the head
    Files usually have .js extension
    <script src="scripts.js" type="text/javscript">
    <!– code placed here will not be executed! -->
    </script>

    Highly recommended
    The .js files get cached by the browser
                                                       12
JavaScript – When is Executed?
 JavaScriptcode is executed during the page
 loading or when the browser fires an event
   All statements are executed at page loading
   Some statements just define functions that can
    be called later
 Function calls
              or code can be attached as
 "event handlers" via tag attributes
   Executed when the event is fired by the browser
  <img src="logo.gif" onclick="alert('clicked!')" />

                                                       13
Calling a JavaScript Function
         from Event Handler – Example
<html>
<head>
<script type="text/javascript">
  function test (message) {
    alert(message);
  }
</script>
</head>

<body>
  <img src="logo.gif"
    onclick="test('clicked!')" />
</body>
</html>

                                           14
Event Handlers
    Live Demo
Using External Script Files
   Using external script files:
    <html>                       external-JavaScript.html
    <head>
      <script src="sample.js" type="text/javascript">
      </script>
    </head>          The <script> tag is always empty.
    <body>
      <button onclick="sample()" value="Call JavaScript
        function from sample.js" />
    </body>
    </html>

   External JavaScript file:
    function sample() {
      alert('Hello from sample.js!')
    }                                          sample.js
                                                            16
External JavaScript Files
         Live Demo
The JavaScript
   Syntax
JavaScript Syntax
 The JavaScript   syntax is similar to C#
   Operators (+, *, =, !=, &&, ++, …)
   Variables (typeless)
   Conditional statements (if, else)
   Loops (for, while)
   Arrays (my_array[]) and associative arrays
    (my_array['abc'])
   Functions (can return value)
   Function variables (like the C# delegates)
                                                 19
Standard Popup Boxes
 Alert box with text and [OK] button

   Just a message shown in a dialog box:
    alert("Some text here");

 Confirmation box

   Contains text, [OK] button and [Cancel] button:
    confirm("Are you sure?");

 Prompt box

   Contains text, input field with default value:
    prompt ("enter amount", 10);
                                                      20
Popup Boxes
  Live Demo
The Built-In
Browser Objects
Built-in Browser Objects
 The browser provides some read-only data via:

  window
    The top node of the DOM tree
    Represents the browser's window
  document
    holds information the current loaded document
  screen
    Holds the user’s display properties
  browser
    Holds information about the browser
                                                     23
DOM Hierarchy – Example


                            window



navigator   screen      document        history   location


                     form      form


                        button        form



                                                             24
Opening New Window – Example
 window.open()

                                window-open.html
 var newWindow = window.open("", "sampleWindow",
   "width=300, height=100, menubar=yes,
   status=yes, resizable=yes");

 newWindow.document.write(
   "<html><head><title>
   Sample Title</title>
   </head><body><h1>Sample
   Text</h1></body>");
 newWindow.status =
   "Hello folks";


                                                   25
The Navigator Object

       alert(window.navigator.userAgent);



The browser   The navigator in the   The userAgent
  window       browser window         (browser ID)




                                                     26
The Screen Object
 The screen object contains   information about
 the display

     window.moveTo(0, 0);
     x = screen.availWidth;
     y = screen.availHeight;
     window.resizeTo(x, y);




                                                   27
Document and Location
 document object

  Provides some built-in arrays of specific objects
   on the currently loaded Web page
  document.links[0].href = "yahoo.com";
  document.write(
    "This is some <b>bold text</b>");
 document.location

  Used to access the currently open URL or
   redirect the browser
  document.location = "http://www.yahoo.com/";
                                                       28
Built-In Browser Objects
         Live Demo
Other JavaScript Objects
The Math Object
 The Math object provides some mathematical
 functions
                                   math.html
  for (i=1; i<=20; i++) {
    var x = Math.random();
    x = 10*x + 1;
    x = Math.floor(x);
    document.write(
      "Random number (" +
      i + ") in range " +
      "1..10 --> " + x +
      "<br/>");
  }

                                               31
The Date Object
 The Date object provides date / calendar
 functions
                                     dates.html
  var now = new Date();
  var result = "It is now " + now;
  document.getElementById("timeField")
    .innerText = result;
  ...
  <p id="timeField"></p>




                                                  32
Timers: setTimeout()
   Make something happen (once) after a fixed
    delay

     var timer = setTimeout('bang()', 5000);

                   5 seconds after this statement
                   executes, this function is called

     clearTimeout(timer);

           Cancels the timer
                                                       33
Timers: setInterval()
   Make something happen repeatedly at fixed
    intervals

    var timer = setInterval('clock()', 1000);

                        This function is called
                      continuously per 1 second.

    clearInterval(timer);

             Stop the timer.

                                                   34
Timer – Example
timer-demo.html
<script type="text/javascript">
  function timerFunc() {
    var now = new Date();
    var hour = now.getHours();
    var min = now.getMinutes();
    var sec = now.getSeconds();
    document.getElementById("clock").value =
      "" + hour + ":" + min + ":" + sec;
  }
  setInterval('timerFunc()', 1000);
</script>
<input type="text" id="clock" />

                                               35
Other JavaScript Objects
         Live Demo
Debugging JavaScript
Debugging JavaScript
 Modern browsers have JavaScript   console
 where errors in scripts are reported
   Errors may differ across browsers
 Several tools to debug JavaScript

   Microsoft Script Editor
    Add-on for Internet Explorer
    Supports breakpoints, watches
    JavaScript statement debugger; opens the script
     editor

                                                       38
Firebug
 Firebug – Firefox add-on for debugging
 JavaScript, CSS, HTML
   Supports breakpoints, watches, JavaScript
    console editor
   Very useful for CSS and HTML too
    You can edit all the document real-time: CSS,
     HTML, etc
    Shows how CSS rules apply to element
   Shows Ajax requests and responses
   Firebug is written mostly in JavaScript
                                                      39
Firebug (2)




              40
JavaScript Console Object
 The console object exists
                          only if there is a
 debugging tool that supports it
  Used to write log messages at runtime
 Methods of the console object:

  debug(message)
  info(message)
  log(message)
  warn(message)
  error(message)
                                               41
Introduction JavaScript
             Development




Questions?
01 Introduction - JavaScript Development

Mais conteúdo relacionado

Mais procurados

Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
helenmga
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
tutorialsruby
 

Mais procurados (18)

JavaScript and BOM events
JavaScript and BOM eventsJavaScript and BOM events
JavaScript and BOM events
 
Dojo: Beautiful Web Apps, Fast
Dojo: Beautiful Web Apps, FastDojo: Beautiful Web Apps, Fast
Dojo: Beautiful Web Apps, Fast
 
Jquery dojo slides
Jquery dojo slidesJquery dojo slides
Jquery dojo slides
 
Arquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com JetpackArquitetando seu aplicativo Android com Jetpack
Arquitetando seu aplicativo Android com Jetpack
 
Evolve your coding with some BDD
Evolve your coding with some BDDEvolve your coding with some BDD
Evolve your coding with some BDD
 
Tapestry 5: Java Power, Scripting Ease
Tapestry 5: Java Power, Scripting EaseTapestry 5: Java Power, Scripting Ease
Tapestry 5: Java Power, Scripting Ease
 
Codemash-Tapestry.pdf
Codemash-Tapestry.pdfCodemash-Tapestry.pdf
Codemash-Tapestry.pdf
 
Skills Matter Itbo April2010 Tapestry
Skills Matter Itbo April2010 TapestrySkills Matter Itbo April2010 Tapestry
Skills Matter Itbo April2010 Tapestry
 
Jquery
JqueryJquery
Jquery
 
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC BelgiquePrésentation et bonnes pratiques du pattern MVVM - MIC Belgique
Présentation et bonnes pratiques du pattern MVVM - MIC Belgique
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
 
Java script
Java scriptJava script
Java script
 
Alfredo-PUMEX
Alfredo-PUMEXAlfredo-PUMEX
Alfredo-PUMEX
 
RicoLiveGrid
RicoLiveGridRicoLiveGrid
RicoLiveGrid
 
Web2 - jQuery
Web2 - jQueryWeb2 - jQuery
Web2 - jQuery
 
A Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NETA Rich Web Experience with jQuery, Ajax and .NET
A Rich Web Experience with jQuery, Ajax and .NET
 
td_mxc_rubyrails_shin
td_mxc_rubyrails_shintd_mxc_rubyrails_shin
td_mxc_rubyrails_shin
 
Web2.0 with jQuery in English
Web2.0 with jQuery in EnglishWeb2.0 with jQuery in English
Web2.0 with jQuery in English
 

Destaque

An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
tonyh1
 
An Introduction to JavaScript: Week One
An Introduction to JavaScript: Week OneAn Introduction to JavaScript: Week One
An Introduction to JavaScript: Week One
Event Handler
 
introduction to javascript
introduction to javascriptintroduction to javascript
introduction to javascript
Kumar
 

Destaque (17)

Learn Javascript Basics
Learn Javascript BasicsLearn Javascript Basics
Learn Javascript Basics
 
JAVA SCRIPT
JAVA SCRIPTJAVA SCRIPT
JAVA SCRIPT
 
JavaScript Introduction
JavaScript IntroductionJavaScript Introduction
JavaScript Introduction
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
An Introduction to JavaScript: Week One
An Introduction to JavaScript: Week OneAn Introduction to JavaScript: Week One
An Introduction to JavaScript: Week One
 
JavaScript Introduction
JavaScript IntroductionJavaScript Introduction
JavaScript Introduction
 
Front-end development introduction (JavaScript). Part 2
Front-end development introduction (JavaScript). Part 2Front-end development introduction (JavaScript). Part 2
Front-end development introduction (JavaScript). Part 2
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
introduction to javascript
introduction to javascriptintroduction to javascript
introduction to javascript
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Java script
Java scriptJava script
Java script
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 
JavaScript code academy - introduction
JavaScript code academy - introductionJavaScript code academy - introduction
JavaScript code academy - introduction
 

Semelhante a 01 Introduction - JavaScript Development

Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
FIWARE
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
Soós Gábor
 

Semelhante a 01 Introduction - JavaScript Development (20)

Jquery Basics
Jquery BasicsJquery Basics
Jquery Basics
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
J query
J queryJ query
J query
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Client-side JavaScript
Client-side JavaScriptClient-side JavaScript
Client-side JavaScript
 
Html5 For Jjugccc2009fall
Html5 For Jjugccc2009fallHtml5 For Jjugccc2009fall
Html5 For Jjugccc2009fall
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMING
 
Developing your first application using FIWARE
Developing your first application using FIWAREDeveloping your first application using FIWARE
Developing your first application using FIWARE
 
Beyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 AppsBeyond HTML: Tools for Building Web 2.0 Apps
Beyond HTML: Tools for Building Web 2.0 Apps
 
Event Programming JavaScript
Event Programming JavaScriptEvent Programming JavaScript
Event Programming JavaScript
 
Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
 
droidQuery: The Android port of jQuery
droidQuery: The Android port of jQuerydroidQuery: The Android port of jQuery
droidQuery: The Android port of jQuery
 
jQuery
jQueryjQuery
jQuery
 
Sanjeev ghai 12
Sanjeev ghai 12Sanjeev ghai 12
Sanjeev ghai 12
 
Jquery beltranhomewrok
Jquery beltranhomewrokJquery beltranhomewrok
Jquery beltranhomewrok
 

Mais de Tommy Vercety

Mais de Tommy Vercety (9)

09. Strings
09. Strings09. Strings
09. Strings
 
08. Objects
08. Objects08. Objects
08. Objects
 
07. Functions
07. Functions07. Functions
07. Functions
 
06. Arrays
06. Arrays06. Arrays
06. Arrays
 
05. Loops
05. Loops05. Loops
05. Loops
 
04. Conditional Statements
04. Conditional Statements04. Conditional Statements
04. Conditional Statements
 
03. Operators - Expressions
03. Operators - Expressions03. Operators - Expressions
03. Operators - Expressions
 
02. Data Type and Variables
02. Data Type and Variables02. Data Type and Variables
02. Data Type and Variables
 
00 JavaScript Part 1 Course - Introduction
00 JavaScript Part 1 Course - Introduction00 JavaScript Part 1 Course - Introduction
00 JavaScript Part 1 Course - Introduction
 

Último

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 

Último (20)

Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 

01 Introduction - JavaScript Development

  • 1. Introduction to JavaScript Development The Magic of Dynamic Web Pages Doncho Minkov Technical Trainer http://minkov.it Telerik Software Academy academy.telerik.com
  • 2. Table of Contents  Dynamic HTML  How to Create DHTML?  XHTML, CSS, JavaScript, DOM  Intro to JavaScript  History  JavaScript in Web Pages  JavaScript Syntax  Pop-up boxes  Debugging in JavaScript 2
  • 3. Dynamic HTML Dynamic Behavior at the Client Side
  • 4. What is DHTML?  Dynamic HTML (DHTML)  Makes possible a Web page to react and change in response to the user’s actions  DHTML consists of HTML + CSS + JavaScript DHTML XHTML CSS JavaScript DOM 4
  • 5. DTHML = HTML + CSS + JavaScript  HTML defines Web sitescontent through semantic tags (headings, paragraphs, lists, …)  CSS defines 'rules' or 'styles' for presenting every aspect of an HTML document  Font (family, size, color, weight, etc.)  Background (color, image, position, repeat)  Position and layout (of any object on the page)  JavaScript defines dynamic behavior  Programming logic for interaction with the user, to handle events, etc. 5
  • 7. JavaScript  JavaScript is a front-end scripting language developed by Netscape for dynamic content  Lightweight, but with limited capabilities  Can be used as object-oriented language  Embedded in your HTML page  Interpreted by the Web browser  Client-side, mobile and desktop technology  Simple and flexible  Powerful to manipulate the DOM 7
  • 8. JavaScript Advantages  JavaScript allows interactivity such as:  Implementing form validation  React to user actions, e.g. handle keys  Changing an image on moving mouse over it  Sections of a page appearing and disappearing  Content loading and changing dynamically  Performing complex calculations  Custom HTML controls, e.g. scrollable table  Implementing AJAX functionality 8
  • 9. What Can JavaScript Do?  Can handle events  Can read and write HTML elements and modify the DOM tree  Can validate form data  Can access / modify browser cookies  Can detect the user’s browser and OS  Can be used as object-oriented language  Can handle exceptions  Can perform asynchronous server calls (AJAX) 9
  • 10. The First Script <html> <body> <script type="text/javascript"> alert('Hello JavaScript!'); </script> </body> </html> 10
  • 11. First JavaScript Live Demo
  • 12. Using JavaScript Code  The JavaScript code can be placed in:  <script> tag in the head  <script> tag in the body - not recommended  External files, linked via <script> tag the head  Files usually have .js extension <script src="scripts.js" type="text/javscript"> <!– code placed here will not be executed! --> </script>  Highly recommended  The .js files get cached by the browser 12
  • 13. JavaScript – When is Executed?  JavaScriptcode is executed during the page loading or when the browser fires an event  All statements are executed at page loading  Some statements just define functions that can be called later  Function calls or code can be attached as "event handlers" via tag attributes  Executed when the event is fired by the browser <img src="logo.gif" onclick="alert('clicked!')" /> 13
  • 14. Calling a JavaScript Function from Event Handler – Example <html> <head> <script type="text/javascript"> function test (message) { alert(message); } </script> </head> <body> <img src="logo.gif" onclick="test('clicked!')" /> </body> </html> 14
  • 15. Event Handlers Live Demo
  • 16. Using External Script Files  Using external script files: <html> external-JavaScript.html <head> <script src="sample.js" type="text/javascript"> </script> </head> The <script> tag is always empty. <body> <button onclick="sample()" value="Call JavaScript function from sample.js" /> </body> </html>  External JavaScript file: function sample() { alert('Hello from sample.js!') } sample.js 16
  • 18. The JavaScript Syntax
  • 19. JavaScript Syntax  The JavaScript syntax is similar to C#  Operators (+, *, =, !=, &&, ++, …)  Variables (typeless)  Conditional statements (if, else)  Loops (for, while)  Arrays (my_array[]) and associative arrays (my_array['abc'])  Functions (can return value)  Function variables (like the C# delegates) 19
  • 20. Standard Popup Boxes  Alert box with text and [OK] button  Just a message shown in a dialog box: alert("Some text here");  Confirmation box  Contains text, [OK] button and [Cancel] button: confirm("Are you sure?");  Prompt box  Contains text, input field with default value: prompt ("enter amount", 10); 20
  • 21. Popup Boxes Live Demo
  • 23. Built-in Browser Objects  The browser provides some read-only data via:  window  The top node of the DOM tree  Represents the browser's window  document  holds information the current loaded document  screen  Holds the user’s display properties  browser  Holds information about the browser 23
  • 24. DOM Hierarchy – Example window navigator screen document history location form form button form 24
  • 25. Opening New Window – Example  window.open() window-open.html var newWindow = window.open("", "sampleWindow", "width=300, height=100, menubar=yes, status=yes, resizable=yes"); newWindow.document.write( "<html><head><title> Sample Title</title> </head><body><h1>Sample Text</h1></body>"); newWindow.status = "Hello folks"; 25
  • 26. The Navigator Object alert(window.navigator.userAgent); The browser The navigator in the The userAgent window browser window (browser ID) 26
  • 27. The Screen Object  The screen object contains information about the display window.moveTo(0, 0); x = screen.availWidth; y = screen.availHeight; window.resizeTo(x, y); 27
  • 28. Document and Location  document object  Provides some built-in arrays of specific objects on the currently loaded Web page document.links[0].href = "yahoo.com"; document.write( "This is some <b>bold text</b>");  document.location  Used to access the currently open URL or redirect the browser document.location = "http://www.yahoo.com/"; 28
  • 31. The Math Object  The Math object provides some mathematical functions math.html for (i=1; i<=20; i++) { var x = Math.random(); x = 10*x + 1; x = Math.floor(x); document.write( "Random number (" + i + ") in range " + "1..10 --> " + x + "<br/>"); } 31
  • 32. The Date Object  The Date object provides date / calendar functions dates.html var now = new Date(); var result = "It is now " + now; document.getElementById("timeField") .innerText = result; ... <p id="timeField"></p> 32
  • 33. Timers: setTimeout()  Make something happen (once) after a fixed delay var timer = setTimeout('bang()', 5000); 5 seconds after this statement executes, this function is called clearTimeout(timer); Cancels the timer 33
  • 34. Timers: setInterval()  Make something happen repeatedly at fixed intervals var timer = setInterval('clock()', 1000); This function is called continuously per 1 second. clearInterval(timer); Stop the timer. 34
  • 35. Timer – Example timer-demo.html <script type="text/javascript"> function timerFunc() { var now = new Date(); var hour = now.getHours(); var min = now.getMinutes(); var sec = now.getSeconds(); document.getElementById("clock").value = "" + hour + ":" + min + ":" + sec; } setInterval('timerFunc()', 1000); </script> <input type="text" id="clock" /> 35
  • 38. Debugging JavaScript  Modern browsers have JavaScript console where errors in scripts are reported  Errors may differ across browsers  Several tools to debug JavaScript  Microsoft Script Editor  Add-on for Internet Explorer  Supports breakpoints, watches  JavaScript statement debugger; opens the script editor 38
  • 39. Firebug  Firebug – Firefox add-on for debugging JavaScript, CSS, HTML  Supports breakpoints, watches, JavaScript console editor  Very useful for CSS and HTML too  You can edit all the document real-time: CSS, HTML, etc  Shows how CSS rules apply to element  Shows Ajax requests and responses  Firebug is written mostly in JavaScript 39
  • 41. JavaScript Console Object  The console object exists only if there is a debugging tool that supports it  Used to write log messages at runtime  Methods of the console object:  debug(message)  info(message)  log(message)  warn(message)  error(message) 41
  • 42. Introduction JavaScript Development Questions?