KEMBAR78
Java Script basics and DOM | PPTX
Sukrit Gupta
sukritgupta91@gmail.com
• Invented by Brendan Eich at Netscape, in1995.
• JavaScript is a programming language designed for Web pages.
• JAVASCRIPT is used to maintain BEHAVIOR of the document.
• JavaScript is used in millions of Web pages to improve the
  design, validate forms, detect browsers, create cookies, and
  much more.
• JavaScript is the most popular scripting language on the
  internet, and works in all major browsers, such as Internet
  Explorer, Mozilla, Firefox, Netscape, Opera.
• JavaScript is an interpreted language (means that scripts execute
  without preliminary compilation)
• Everyone can use JavaScript without purchasing a license
• Unlike HTML, JavaScript is case sensitive.
 Requires the JDK to create        Requires a text editor
  the applet
                                    Required a browser that can
 Requires a Java virtual            interpret JavaScript code
  machine to run the applet
                                    JavaScript can be placed
 Applet files are distinct from
  the HTML code                      within HTML and XHTML

 Source code is hidden from        Source code is made
  the user                           accessible to the user
 Programs must be saved as         Programs cannot write
  separate files and compiled        content to the hard disk
  before they can be run
                                    Programs run on the client
 Programs run on the server         side
  side
• JavaScript code is included within <script> tags:
   • <script type="text/javascript">
        document.write("<h1>Hello World!</h1>") ;
     </script>
• Notes:
    • The type attribute is to allow to use other scripting languages (but
       JavaScript is the default)
    • This simple code does the same thing as just putting <h1>Hello
       World!</h1> in the same place in the HTML document
    • The semicolon at the end of the JavaScript statement is optional.
    • We need semicolons if you put two or more statements on the
       same line.
• JavaScript can be put in the <head> or in the <body> of an HTML
  document
    • JavaScript functions should be defined in the <head>
        • This ensures that the function is loaded before it is needed
    • JavaScript in the <body> will be executed as the page loads
• JavaScript functions can be put in a separate .js file
   • <script src="myJavaScriptFile.js"></script>
    • Put this in the <head>
    • An external .js file lets us use the same JavaScript on multiple
       HTML pages
    • The external .js file cannot itself contain a <script> tag
• JavaScript can be put in an HTML form Object, such as a button
    • This JavaScript will be executed when the form object is used
• Some old browsers do not recognize script tags
   •   These browsers will ignore the script tags but will display the included
       JavaScript
   •   To get old browsers to ignore the whole thing, use:
          <script type="text/javascript">
          <!--
             document.write("Hello World!")
          //-->
          </script>
   •   The <!-- introduces an HTML comment
   •   To get JavaScript to ignore the HTML close comment, -->, the // starts
       a JavaScript comment, which extends to the end of the line
• Some users turn off JavaScript
   •   Use the <noscript>message</noscript> to display a message in place
       of whatever the JavaScript would put there
Manipulating HTML Elements       Writing to The Document Output
• <p id="demo">My First
                                   • <h1>My First Web Page</h1>
  Paragraph</p>
                                   <script>
  <script>                                   document.write("<p>My First
  document.getElementById("demo"             JavaScript</p>");
  ).innerHTML="My First            </script>
  JavaScript";
  </script>
• Variables are declared with a var statement:
   • var pi = 3.1416, x, y, name = "Dr. Dave" ;
   • Variables names must begin with a letter or underscore
   • Variable names are case-sensitive
   • Variables are untyped (they can hold values of any type)
   • The word var is optional
  Variables declared within a function are local to that function
   (accessible only within that function)
• Variables declared outside a function are global (accessible from
  anywhere on the page)
• Dynamic Typing - Variables can hold any valid type of value:
– Number … var myInt = 7;
– Boolean … var myBool = true;
– Function …var fname= function() { ……. };
– Object …... var person={firstname:"John", lastname:"Doe", id:5566};
– Array ……. var myArr = new Array();
– String …….var myString = ―abc‖;
– … and can hold values of different types at different times during
         execution.
Arithmetic Operators   Assignment Operators
Comparison Operators   Logical Operators
Alert Box                                  Confirm Box
                                       A confirm box is often used if we
 An alert box is often used if we      want the user to verify or accept
 want to make sure information          something.
 comes through to the user.
                                       When a confirm box pops up, the
 When an alert box pops up, the        user will have to click either "OK" or
 user will have to click "OK" to        "Cancel" to proceed.
 proceed.
<script>alert("Hello World!")</script>  If the user clicks "OK", the box
                                         returns true. If the user clicks
                                         "Cancel", the box returns false.
                                       • <script>confirm(―Sure??")</script>
•   Prompt Box
   • A prompt box is often used if we want the user to input a value .
   • When a prompt box pops up, the user will have to click either "OK"
       or "Cancel" to proceed after entering an input value.
   • If the user clicks "OK―, the box returns the input value. If the user
       clicks "Cancel―, the box returns null.
• <script> var name=prompt("Please enter your name","Harry");</script>
•       „if‟ statement
    •      if ( boolean statement ) {…}    else {…}
•       „switch‟ statement
    •      switch ( myVar ) {
    •                case 1:              // if myVar is equal to 1 this is executed
    •                break;
    •                case “two”:          // if myVar is equal to “two” this is executed
    •                break;
    •                case default:        // if none of the cases above are satisfied OR if no
    •                                     // „break‟ statement are used in the cases above,
    •                                     // this will be executed
    •               }
•       The For Loop
    •     SYNTAX:            for (start; condition; update) {JavaScript
          Commands}
    •     start is the starting value of the counter.
    •     condition is a Boolean expression that must be true for the loop to
          continue
    •     update specifies how the counter changes in value each time the
          command block is executed
    •     Example             for (var i=0; i<4; i++) { j++; }
•       The While Loop
    •     SYNTAX:          while (condition) { JavaScript Commands}
    •     condition is a Boolean expression that can be either true or false
    •     Example          while (var i<=10) { j++; i++;}
•       The Do While Loop
    •     SYNTAX:          do statement while (condition);
• Functions should be defined in the <head> of an HTML page, to ensure
   that they are loaded first
 • The syntax for defining a function is:
                function fname(arg1, …, argN) { statements }
 • The function may return value.
 • Any variables declared within the function are local to it.
 • The syntax for calling a function is just
                name(arg1, …, argN)
 • Simple parameters are passed by value, objects are passed by
   reference
• Function names are case-sensitive.
• There is no limit to the number of function parameters that a function
  may contain.


   •
• An object is just a special kind of data, with properties and methods.
  • Almost everything in JavaScript is an Object: String, Number, Array,
    Function, image.... Ex document.bgcolor          document.write(‖Hello");
  •                                                   document is the object. is the object.
                                                                   document
  •                                                   bgcolor is the property. method.
                                                                   write is the
• We can also create our own objects:
      •   SYNTAX: { name1 : value1 , ... , nameN : valueN }
      •   EXAMPLE: car = {myCar: "Saturn", variant: "Mazda", special: Sales}
      •   Example use: document.write("I own a " + car.myCar);

      •   Using new:
          •   var course = new Object();     •   Using a constructor:
              course.number = "CIT597";
                                                 •   function Course(n, t) { // best placed in <head>
              course.teacher = "Dr. Dave";
                                                        this.number = n;     // keyword "this" is required,
                                                         this.teacher = t;       //not optional
                                                     }
                                                 •   var course = new Course("CIT597", "Dr. Dave");

      •
• Events are actions that occur usually as a result of something the user
  does. For example, clicking a button is an event, as is changing a text
  field or moving the mouse over a hyperlink.
• We write our scripts so they execute by reacting to events within a web
  browser.
• Since events are at the heart of JavaScript programming, we need a way
  to detect events. We do that by using built-in event handlers …
• Eg: Click, change, focus, load, mouseover, mouseout, reset, submit.
         <input type=―button‖ onClick=―javascript:doButton()‖>
    • //calls function when button is clicked.
           <body onLoad=―javascript:init()‖>
•    //calls   function when page is loaded.




     •
•
• DOM stands for Document Object
  Model.
• It is a platform and language-neutral
  interface that allows programs and
  scripts to dynamically access and
  update the content, structure, and style
  of a document.
• The HTML DOM defines a standard for
  accessing and manipulating HTML
  documents.
• DOM is a tree of Objects
• Contents can be modified or deleted
• New elements can be created and
  inserted into the DOM Tree
• The document object is the JavaScript interface to the DOM of any HTML
  page.
• Accessing elements:
        – By name
   •                    document.getElementsByTagName(‗td')[indexOfColumn];
   •           –By ID
   •                    document.getElementById('id');
   •           – Walk the DOM Tree
   •                    document.childNodes[0].childNodes[1].childNodes[4];


       •
• JavaScript provides some limited, persistent storage, called
  cookies:
   •– Data is stored in a text file on the client
   •– name=value
   •–Multiple values are delimited by a semicolon
• Use sparingly. There are limits (generally):
   •– Up to 300 cookies per browser, 20 cookies per web server, and 4 KB of data
   per cookie
• Don‘t depend on cookies—users can block or delete them.
• By default, cookies are destroyed when the browser window is
  closed, unless we explicitly set the expires attribute.
   • – To persist a cookie, set the expires attribute to a future date.
   • – To delete a cookie, set the expires attribute to a past date.
• By default, cookies can only be read by the web page that wrote
  them unless we specify one or more of these attributes:
   • – path – allows more than one page on the site to read a cookie.(default value:
     /)
   • – domain – allows multiple servers to read a cookie.
   • -name – An identifier by which we reference a particular cookie.
   • -value – The information we wish to save, in reference to a particular cookie.
   • -expires – A GMT-formatted date specifying the date (in milliseconds) when a
     cookie will expire.
  SYNTAX to create a cookie:
    •   document.cookie = "username=" + who + ";‖ + "expires=" + expDate.toGMTString();+
        ―path=/‖
• Difficult because the language is interpreted.
   • – No compiler errors/warnings.
   • – Browser will try to run the script, errors and all.
• Make each line as granular as possible (use variables).
• Use alerts to get values of variables and see which lines are not
  getting processed.
• When testing form validation, set the action attribute to a dummy
  HTML page—not the server-side form. If you get the page, the
  script works.
• Try add-on like Firebug to detect problem.
• JavaScript is not totally platform independent
   • – Expect different browsers to behave differently
   • – Check whether the browser supports the functionality or not.
Java Script basics and DOM

Java Script basics and DOM

  • 1.
  • 2.
    • Invented byBrendan Eich at Netscape, in1995. • JavaScript is a programming language designed for Web pages. • JAVASCRIPT is used to maintain BEHAVIOR of the document. • JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more. • JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Mozilla, Firefox, Netscape, Opera. • JavaScript is an interpreted language (means that scripts execute without preliminary compilation) • Everyone can use JavaScript without purchasing a license • Unlike HTML, JavaScript is case sensitive.
  • 3.
     Requires theJDK to create  Requires a text editor the applet  Required a browser that can  Requires a Java virtual interpret JavaScript code machine to run the applet  JavaScript can be placed  Applet files are distinct from the HTML code within HTML and XHTML  Source code is hidden from  Source code is made the user accessible to the user  Programs must be saved as  Programs cannot write separate files and compiled content to the hard disk before they can be run  Programs run on the client  Programs run on the server side side
  • 4.
    • JavaScript codeis included within <script> tags: • <script type="text/javascript"> document.write("<h1>Hello World!</h1>") ; </script> • Notes: • The type attribute is to allow to use other scripting languages (but JavaScript is the default) • This simple code does the same thing as just putting <h1>Hello World!</h1> in the same place in the HTML document • The semicolon at the end of the JavaScript statement is optional. • We need semicolons if you put two or more statements on the same line.
  • 5.
    • JavaScript canbe put in the <head> or in the <body> of an HTML document • JavaScript functions should be defined in the <head> • This ensures that the function is loaded before it is needed • JavaScript in the <body> will be executed as the page loads • JavaScript functions can be put in a separate .js file • <script src="myJavaScriptFile.js"></script> • Put this in the <head> • An external .js file lets us use the same JavaScript on multiple HTML pages • The external .js file cannot itself contain a <script> tag • JavaScript can be put in an HTML form Object, such as a button • This JavaScript will be executed when the form object is used
  • 6.
    • Some oldbrowsers do not recognize script tags • These browsers will ignore the script tags but will display the included JavaScript • To get old browsers to ignore the whole thing, use: <script type="text/javascript"> <!-- document.write("Hello World!") //--> </script> • The <!-- introduces an HTML comment • To get JavaScript to ignore the HTML close comment, -->, the // starts a JavaScript comment, which extends to the end of the line • Some users turn off JavaScript • Use the <noscript>message</noscript> to display a message in place of whatever the JavaScript would put there
  • 7.
    Manipulating HTML Elements Writing to The Document Output • <p id="demo">My First • <h1>My First Web Page</h1> Paragraph</p> <script> <script> document.write("<p>My First document.getElementById("demo" JavaScript</p>"); ).innerHTML="My First </script> JavaScript"; </script>
  • 8.
    • Variables aredeclared with a var statement: • var pi = 3.1416, x, y, name = "Dr. Dave" ; • Variables names must begin with a letter or underscore • Variable names are case-sensitive • Variables are untyped (they can hold values of any type) • The word var is optional  Variables declared within a function are local to that function (accessible only within that function) • Variables declared outside a function are global (accessible from anywhere on the page)
  • 9.
    • Dynamic Typing- Variables can hold any valid type of value: – Number … var myInt = 7; – Boolean … var myBool = true; – Function …var fname= function() { ……. }; – Object …... var person={firstname:"John", lastname:"Doe", id:5566}; – Array ……. var myArr = new Array(); – String …….var myString = ―abc‖; – … and can hold values of different types at different times during execution.
  • 10.
    Arithmetic Operators Assignment Operators
  • 11.
    Comparison Operators Logical Operators
  • 12.
    Alert Box Confirm Box  A confirm box is often used if we An alert box is often used if we want the user to verify or accept want to make sure information something. comes through to the user.  When a confirm box pops up, the When an alert box pops up, the user will have to click either "OK" or user will have to click "OK" to "Cancel" to proceed. proceed. <script>alert("Hello World!")</script>  If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. • <script>confirm(―Sure??")</script>
  • 13.
    Prompt Box • A prompt box is often used if we want the user to input a value . • When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value. • If the user clicks "OK―, the box returns the input value. If the user clicks "Cancel―, the box returns null. • <script> var name=prompt("Please enter your name","Harry");</script>
  • 14.
    „if‟ statement • if ( boolean statement ) {…} else {…} • „switch‟ statement • switch ( myVar ) { • case 1: // if myVar is equal to 1 this is executed • break; • case “two”: // if myVar is equal to “two” this is executed • break; • case default: // if none of the cases above are satisfied OR if no • // „break‟ statement are used in the cases above, • // this will be executed • }
  • 15.
    The For Loop • SYNTAX: for (start; condition; update) {JavaScript Commands} • start is the starting value of the counter. • condition is a Boolean expression that must be true for the loop to continue • update specifies how the counter changes in value each time the command block is executed • Example for (var i=0; i<4; i++) { j++; } • The While Loop • SYNTAX: while (condition) { JavaScript Commands} • condition is a Boolean expression that can be either true or false • Example while (var i<=10) { j++; i++;} • The Do While Loop • SYNTAX: do statement while (condition);
  • 16.
    • Functions shouldbe defined in the <head> of an HTML page, to ensure that they are loaded first • The syntax for defining a function is: function fname(arg1, …, argN) { statements } • The function may return value. • Any variables declared within the function are local to it. • The syntax for calling a function is just name(arg1, …, argN) • Simple parameters are passed by value, objects are passed by reference • Function names are case-sensitive. • There is no limit to the number of function parameters that a function may contain. •
  • 17.
    • An objectis just a special kind of data, with properties and methods. • Almost everything in JavaScript is an Object: String, Number, Array, Function, image.... Ex document.bgcolor document.write(‖Hello"); • document is the object. is the object. document • bgcolor is the property. method. write is the • We can also create our own objects: • SYNTAX: { name1 : value1 , ... , nameN : valueN } • EXAMPLE: car = {myCar: "Saturn", variant: "Mazda", special: Sales} • Example use: document.write("I own a " + car.myCar); • Using new: • var course = new Object(); • Using a constructor: course.number = "CIT597"; • function Course(n, t) { // best placed in <head> course.teacher = "Dr. Dave"; this.number = n; // keyword "this" is required, this.teacher = t; //not optional } • var course = new Course("CIT597", "Dr. Dave"); •
  • 18.
    • Events areactions that occur usually as a result of something the user does. For example, clicking a button is an event, as is changing a text field or moving the mouse over a hyperlink. • We write our scripts so they execute by reacting to events within a web browser. • Since events are at the heart of JavaScript programming, we need a way to detect events. We do that by using built-in event handlers … • Eg: Click, change, focus, load, mouseover, mouseout, reset, submit. <input type=―button‖ onClick=―javascript:doButton()‖> • //calls function when button is clicked. <body onLoad=―javascript:init()‖> • //calls function when page is loaded. •
  • 19.
  • 20.
    • DOM standsfor Document Object Model. • It is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document. • The HTML DOM defines a standard for accessing and manipulating HTML documents. • DOM is a tree of Objects • Contents can be modified or deleted • New elements can be created and inserted into the DOM Tree
  • 21.
    • The documentobject is the JavaScript interface to the DOM of any HTML page. • Accessing elements: – By name • document.getElementsByTagName(‗td')[indexOfColumn]; • –By ID • document.getElementById('id'); • – Walk the DOM Tree • document.childNodes[0].childNodes[1].childNodes[4]; •
  • 22.
    • JavaScript providessome limited, persistent storage, called cookies: •– Data is stored in a text file on the client •– name=value •–Multiple values are delimited by a semicolon • Use sparingly. There are limits (generally): •– Up to 300 cookies per browser, 20 cookies per web server, and 4 KB of data per cookie • Don‘t depend on cookies—users can block or delete them.
  • 23.
    • By default,cookies are destroyed when the browser window is closed, unless we explicitly set the expires attribute. • – To persist a cookie, set the expires attribute to a future date. • – To delete a cookie, set the expires attribute to a past date. • By default, cookies can only be read by the web page that wrote them unless we specify one or more of these attributes: • – path – allows more than one page on the site to read a cookie.(default value: /) • – domain – allows multiple servers to read a cookie. • -name – An identifier by which we reference a particular cookie. • -value – The information we wish to save, in reference to a particular cookie. • -expires – A GMT-formatted date specifying the date (in milliseconds) when a cookie will expire.  SYNTAX to create a cookie: • document.cookie = "username=" + who + ";‖ + "expires=" + expDate.toGMTString();+ ―path=/‖
  • 24.
    • Difficult becausethe language is interpreted. • – No compiler errors/warnings. • – Browser will try to run the script, errors and all. • Make each line as granular as possible (use variables). • Use alerts to get values of variables and see which lines are not getting processed. • When testing form validation, set the action attribute to a dummy HTML page—not the server-side form. If you get the page, the script works. • Try add-on like Firebug to detect problem. • JavaScript is not totally platform independent • – Expect different browsers to behave differently • – Check whether the browser supports the functionality or not.