SlideShare a Scribd company logo
JAVASCRIPT



  By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Introduction
      JavaScript is the most popular scripting
language on the internet, and works in all major
browsers, such as Internet Explorer, Firefox,
Chrome, Opera, and Safari.



What You Should Already Know?
Before you continue you should have a basic
understanding of the following:
HTML and CSS


                 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
What is JavaScript?
• scripting language
• add interactivity to HTML pages
•A scripting language is a lightweight programming language
•JavaScript is usually embedded directly into HTML pages
•JavaScript is an interpreted language (means that scripts execute
without preliminary compilation)

•Everyone can use JavaScript without purchasing a license

                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Java and JavaScript
•Java and JavaScript are not same.

•Java and JavaScript are two completely different languages in
both concept and design.




•Java (developed by Sun Microsystems) is a powerful and much
more complex programming language - in the same category as C

and C++.
                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
What Can JavaScript do?
•JavaScript gives HTML designers a programming tool - HTML authors
are normally not programmers, but JavaScript is a scripting language with a

very simple syntax. Almost anyone can put small "snippets" of code into their

HTML pages

•JavaScript can react to events - A JavaScript can be set to execute when
something happens, like when a page has finished loading or when a user

clicks on an HTML element

•JavaScript can read and write HTML elements - A JavaScript can read
and change the content of an HTML element

                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
What Can JavaScript do?
•JavaScript can be used to validate data - A JavaScript can be used to
validate form data before it is submitted to a server. This saves the server from

extra processing

•JavaScript can be used to detect the visitor's browser - A JavaScript can
be used to detect the visitor's browser, and - depending on the browser - load

another page specifically designed for that browser

•JavaScript can be used to create cookies - A JavaScript can be used to
store and retrieve information on the visitor's computer


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Brief History of JavaScript
•JavaScript is an implementation of the ECMAScript language standard.
ECMA-262 is the official JavaScript standard.

•JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0),
and has appeared in all browsers since 1996.

•The official standardization was adopted by the ECMA organization (an
industry standardization association) in 1997.

•The ECMA standard (called ECMAScript-262) was approved as an
international ISO (ISO/IEC 16262) standard in 1998.

•The development is still in progress.
                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript: Display Date
<html>
          <head>
                 <title>Javascript</title>
          </head>
          <body>
                 <h1>My First Web Page</h1>
                 <script type="text/javascript">
                         document.write("<p>" + Date() + "</p>");
                 </script>
          </body>
</html>




                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
<script> Tag

•To insert a JavaScript into an HTML page, use the
<script> tag.

•Inside the <script> tag use the type attribute to define the
scripting language.

•The <script> and </script> tells where the JavaScript
starts and ends.

•Without the <script> tag(s), the browser will treat
"document.write" as pure text and just write it to the page.
                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript: comments
•    JavaScript comments can be used to make the code more readable.

•    Comments can be added to explain the JavaScript

•    There are Two types of comments in JavaScript:
          1) Single line comments
          2) Multi-Line comments
1)     Single line comments start with //.
e.g.      <script type="text/javascript">
                      // Write a heading
                      document.write("<h1>This is a heading</h1>");
                      // Write two paragraphs:
                      document.write("<p>This is a paragraph.</p>");
                      document.write("<p>This is another paragraph.</p>");
          </script>


                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript: comments
2) Multi-Line Comments
       Multi line comments start with /* and end with */.
e.g.
       <script type="text/javascript">
       /*
       The code below will write
       one heading and two paragraphs
       */
       document.write("<h1>This is a heading</h1>");
       document.write("<p>This is a paragraph.</p>");
       document.write("<p>This is another paragraph.</p>");
       </script>




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript: comments
•   Use of JavaScript comments
    1) To Prevent Execution
    2) At the End of a Line
1) To Prevent Execution: The comment is used to prevent the execution of
         i) single code line:
     e.g.               <script type="text/javascript">
            //document.write("<h1>This is a heading</h1>");
            document.write("<p>This is a paragraph.</p>");
            document.write("<p>This is another paragraph.</p>");

            </script>

         ii) code block:
     e.g. <script type="text/javascript">
         /*document.write("<h1>This is a heading</h1>");
         document.write("<p>This is a paragraph.</p>");
         document.write("<p>This is another paragraph.</p>");*/
         </script>
                                 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript: comments


2) At the End of a Line :




e.g.     <script type="text/javascript">
         document.write("Hello"); // Write "Hello"
         document.write("World!"); // Write "World!"
         </script>




                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript: comments
•   Browsers that do not support JavaScript, will display JavaScript as page content.

•   To prevent them from doing this, and as a part of the JavaScript standard, the HTML
    comment tag should be used to "hide" the JavaScript.

•   Just add an HTML comment tag <!-- before the first JavaScript statement, and a -->
    (end of comment) after the last JavaScript statement, like this:
    <html>
                      <body>
                                 <script type="text/javascript">
                                 <!--

                                 document.write("<p>" + Date() + "</p>");
                                 //-->
                                 </script>
                      </body>
          /html>
The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This
    prevents JavaScript from executing the --> tag.


                                By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Placing JavaScript
1)Scripts in <head> and <body>:
       You can place an unlimited number of scripts in your document, and you
       can have scripts in both the body and the head section at the same time.
       It is a common practice to put all functions in the head section, or at the
       bottom of the page. This way they are all in one place and do not interfere
       with page content.


                  e.g.     JavaScript in <body>
                      <html>
                                   <body>
                                   <h1>My First Web Page</h1>
                                   <p id="demo"></p>
                                   <script type="text/javascript">

                     document.getElementById("demo").innerHTML=Date();
                                           </script>
                         </body>
                         </html>
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Placing JavaScript
e.g.     JavaScript in <head>
<html>
     <head>
                 <script type="text/javascript">
                 function displayDate()
                           {

   document.getElementById("demo").innerHTML=Date();
                            }
                  </script>
         </head>
   <body>
         <h1>My First Web Page</h1>
         <p id="demo"></p>
   <button type="button" onclick="displayDate()">Display
   Date</button>
   </body>
   </html>
        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Placing JavaScript
2) Using an External JavaScript :

JavaScript can also be placed in external files.

External JavaScript files often contain code to be used on several different web pages.

External JavaScript files have the file extension .js.

Note:     External script cannot contain the <script></script> tags

        To use an external script, point to the .js file in the "src"   attribute of the

          <script> tag:
     e.g. <html>
                     <head>
                              <script type="text/javascript" src=“abc.js"></script>
                    </head>
                    <body>
                    </body>
          </html>

                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Writing JavaScript
•   JavaScript is Case Sensitive

•   JavaScript Statements : JavaScript is a sequence of statements to be

    executed by the browser. A JavaScript statement is a command to a browser

    e.g. document.write("Hello World");


•   JavaScript Code:
    <script type="text/javascript">
                     document.write("<h1>This is a heading</h1>");
                     document.write("<p>This is a paragraph.</p>");
                     document.write("<p>This is another paragraph.</p>");
         </script>



                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Writing JavaScript
•   JavaScript Blocks:

e.g.

<script type="text/javascript">

         {

                 document.write("<h1>This is a heading</h1>");

                 document.write("<p>This is a paragraph.</p>");

                 document.write("<p>This is another paragraph.</p>");

    }

    </script>


                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Variables
•   Variables are "containers" for storing information.

•   JavaScript variables are used to hold
    i) values e.g. x=5
    ii) expressions e.g. z=x+y. .

•   A variable can have a short name, like x, or a more descriptive
    name, like myname.
Rules for JavaScript variable names:
•   Variable names are case sensitive (y and Y are two different
    variables)

•   Variable names must begin with a letter or the underscore
    character

                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Variables
Declaring JavaScript Variables
•   Creating variables in JavaScript is most often referred to as "declaring"
    variables.
•   You declare JavaScript variables with the var keyword:
          var x;
          var carname;
•   After the declaration the variables are empty
•   assigning values
          var x=5;
          var carname="Volvo";
•   When you assign a text value to a variable, use quotes around the value.
•    If you redeclare a JavaScript variable, it will not lose its value.




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Variables
•   A variable's value can change during the execution of a script. You can
   refer to a variable by its name to display or change its value.
e.g.
<html>
   <head>
         <title>Variables in JavaScript</title>
   </head>
   <body>
         <h1>Variables in JavaScript</h1>
         <script type="text/javascript">
                  var firstname;
                  firstname="xyz";
                  document.write(firstname);
                  document.write("<br>");
                  firstname="abc";
                  document.write(firstname);
                  document.write("<br>");
                  var firstname;
                  document.write(firstname);
         </script>
   </body></html>           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Scope Of JavaScript Variables
Local JavaScript Variables
•   A variable declared within a JavaScript function becomes LOCAL and can
    only be accessed within that function. (the variable has local scope).

•   You can have local variables with the same name in different functions,
    because local variables are only recognized by the function in which they
    are declared.

•   Local variables are destroyed when you exit the function.
Global JavaScript Variables
•   Variables declared outside a function become GLOBAL, and all scripts
    and functions on the web page can access it.

•   Global variables are destroyed when you close the page.

•   If you declare a variable, without using "var", the variable always
    becomes GLOBAL.

                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Variables
Assigning Values to Undeclared JavaScript Variables:
If you assign values to variables that have not yet been declared, the
   variables will automatically be declared as global variables.
These statements:
        x=5;
        carname="Volvo";
will declare the variables x and carname as global variables (if they don't
   already exist).
JavaScript Arithmetic:
As with algebra, you can do arithmetic operations with JavaScript variables:
   y=x-5;
   z=y+5;


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Assignments

Assignment No. 2:

1. Explain different Text Formatting Tags in HTML with example.

2. Describe local and remote links in HTML with example.

3. What are the different types of lists in HTML. Explain with examples.

4. Explain methods for adding graphics in HTML

5. Explain Table creation in HTML with appropriate examples.




                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Assignments

Assignment No. 3:

1.    Describe Image Maps in HTML with example.


2.    What are the different ways for defining Style Sheet properties in
     Cascading Style Sheet. Explain with appropriate examples.

3.    What are the different types of SELECTORS that can be used in
     Cascading Style Sheet. Explain with appropriate examples.

4.    Explain different elements in HTML forms that can be added to build
     interactivity.

5. Describe various HTML editors.



                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Data Types In JavaScript
There are six data types in JavaScript :
• Numbers
• Strings
• Booleans
• Null
• Undefined
• Objects

              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Data Types In JavaScript
Numbers: Numbers in JavaScript consist of integers, floats, hexadecimals,
   octal i.e. all numbers are valid in JavaScript.
e.g. 4,51.50,-14,0xd
<html>
   <head>
        <title>Hexadecimal Numbers</title>
   </head>
   <body>
        <h1>My First Web Page</h1>
        <script type"text/css">
                 var h=0xe;
                 var i=0x2;
                 var j=h*i;
                 alert(j);
        </script>
   </body>
</html>

                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Data Types In JavaScript
Strings:
Strings consist of one or more characters surrounded by quotes.
e.g.      “Hello World”,
          “B”,
          “This is ‘another string’”


    If you need to use the same style of quotes both to enclose the string and within
    string, then the quotes must be escaped. A single backslash character escapes
    the quote
e.g.

•   ‘i’m using single quote both outside and within this example. They’re neat.’

•   “This is a ”great” example of using ”double quotes” within a string.”


                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
The table below lists other special characters that can
be added to a text string with the backslash sign:


     Code                    Outputs
     '                      single quote
     "                      double quote
                           backslash
     n                      new line
     r                      carriage return
     t                      tab
     b                      backspace
     f                      form feed

                  By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Data Types In JavaScript
Booleans:
  Booleans have only two values, true and false.
  Booleans are bit of a hidden data type in JavaScript i.e. you
  don’t work with Booleans in the same way that you work
  with strings and numbers. You simply use an expression
  that evaluates to a Boolean value.
e.g.
       If (mynumber>18) {
              //do something
       }
                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Data Types In JavaScript
Null :
   Null is special data type in JavaScript. Null is simply
  nothing. It represents and evaluates to false.
Undefined:
  Undefined is a state, sometimes used like a value, to
  represent a variable that hasn’t yet contained a value.
Objects:
  JavaScript objects are a collection of properties, each of
  which contains a primitive value. You can define your own
  objects using JavaScript, and there are several build-in
  objects as well.   By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
  The ECMA-262 standard defines assorted operators of
  various forms. These include:
1. Additive operators
2. Multiplicative operators
3. Bitwise operators
4. Equality operators
5. Relational operators
6. Unary operators
7. Assignment operators


                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
1. Additive operators:

 Operator        Description               Example           Result
 +               Addition                  x=y+2             x=7         y=5
 -               Subtraction               x=y-2             x=3         y=5

     The Addition operator operates in different ways depending on the
     type of value being added. When a string is used, the addition
     operator concatenates the left and right arguments.
 e.g. var str1=“hello”;
      var str2=“ world”;
      var result=str1+str2; // result will be the string “hello world”


                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
2. Multiplicative operators :




 Operator Description               Example        Result
 *          Multiplication          x=y*2          x=10       y=5
 /          Division                x=y/2          x=2.5      y=5
 %          Modulus (division       x=y%2          x=1        y=5
            remainder)




                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
3. Bitwise operators :
   Operator Description
   &          AND
   |          OR
   ^          XOR
   ~          NOT
   <<         Shift Left
   >>         Shift Right




                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
4. Equality operators :
   Operator Description
   ==         Tests whether two expressions are equal
   !=         Tests whether two expressions are not equal
   ===        Tests whether two expressions are equal
              using stricter methods
   !==        Tests whether two expressions are not equal
              using stricter methods


   The stricter of two(===) requires not only that the values
   of a given expression are equal, but the types as well.



                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
5. Relational operators :
  Operator     Description
  >            Greater than
  <            Less than
  >=           Greater than or equal to
  <=           Less than or equal to
  in           Tests whether a value is found in an
               expression
  instanceof   Tests whether an expression is an instance of
               an object




                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
6. Unary operators :
  Operator   Description
  delete     Removes a property
  void       Returns Undefined
  typeof     Returns a string representing the data type
  ++         Increments a number
  --         decrements a number
  +          Converts the operand to a number
  -          Negates the operand
  ~          Bitwise NOT
  !          Logical NOT



                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Operators
7. Assignment operators :
 Operator       Example             Same As            Result
 =              x=y                                    x=5
 +=             x+=y                x=x+y              x=15
 -=             x-=y                x=x-y              x=5
 *=             x*=y                x=x*y              x=50
 /=             x/=y                x=x/y              x=2
 %=             x%=y                x=x%y              x=0




                  By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
       Conditional statements are used to perform different
actions based on different conditions.
In JavaScript we have the following conditional statements:

• if statement - use this statement to execute some code only if
a specified condition is true

• if...else statement - use this statement to execute some code if
the condition is true and another code if the condition is false

• if...else if....else statement - use this statement to select one
of many blocks of code to be executed

• switch statement - use this statement to select one of many
blocks of code to be executed
                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
if Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax : if (condition)
            {
            code to be executed if condition is true
            }
e.g. <html>
         <head>
                   <title>If statement</title>
         </head>
         <body>
                   <script type="text/javascript">
                               var d = new Date();
                               var time = d.getHours();
                               if (time < 10)
                                 {
                                 document.write("<b>Good morning</b>");
                                 }
                   </script>
                   <p>This example demonstrates the If statement.</p>
                   <p>If the time on your browser is less than 10, you will get a "Good
                               morning" greeting.</p>
         </body></html>

                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
If...else Statement :
        Use the if....else statement to execute some code if a condition is
true and another code if the condition is not true.

Syntax :
             if (condition)
              {
              code to be executed if condition is true
              }
             else
              {
              code to be executed if condition is not true
              }

                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
<html>
          <head>
                    <title>If else statement</title>
          </head>
          <body>
                    <script type="text/javascript">
                               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>
                    <p>This example demonstrates the If...Else statement.         </p>
                    <p>
                               If the time on your browser is less than 10,
                               you will get a "Good morning" greeting.
                               Otherwise you will get a "Good day" greeting.
                    </p>
          </body>
</html>


                               By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
If...else if...else Statement :
        Use the if....else if...else statement to select one of several blocks of
code to be executed.

Syntax :         if (condition1)
                  {
                  code to be executed if condition1 is true
                  }
                 else if (condition2)
                  {
                  code to be executed if condition2 is true
                  }
                 else
                  {
                  code to be executed if neither condition1 nor condition2 is true
                  }        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
<html>
          <head>
                    <title>If else if statement</title>
          </head>
          <body>
                    <script type="text/javascript">
                              var d = new Date();
                              var time = d.getHours();
                              if (time<10)
                              {
                                          document.write("<b>Good morning</b>");
                              }
                              else if (time>=10 && time<16)
                              {
                                          document.write("<b>Good day</b>");
                              }
                              else
                              {
                                          document.write("<b>Hello World!</b>");
                              }
                    </script>
                    <p>This example demonstrates the if..else if...else statement.</p>
          </body>
</html>                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
The JavaScript Switch Statement
Use the switch statement to select one of many blocks of code to be
executed.

Syntax :        switch(n)
                {
                case 1:
                              execute code block 1
                             break;
                case 2:
                              execute code block 2
                             break;
                default:
                             code to be executed if n is different from case 1 and 2
                }           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Conditional Statements
<html>
         <head>
                   <title>switch statement</title>
         </head>
         <body>
                   <script type="text/javascript">
                              var d=new Date();
                              var theDay=d.getDay();
                              switch (theDay)
                              {
                              case 5:
                                          document.write("<b>Finally Friday</b>");
                                          break;
                              case 6:
                                          document.write("<b>Super Saturday</b>");
                                          break;
                              case 0:
                                          document.write("<b>Sleepy Sunday</b>");
                                          break;
                              default:
                                          document.write("<b>I'm really looking forward to this
                                                   weekend!</b>");
                              }
                   </script>
                   <p>This JavaScript will generate a different greeting based on what day it
is.
                   Note that Sunday=0, Monday=1, Tuesday=2, etc.</p>
         </body>              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Dialog boxes


JavaScript has three kind of dialog boxes:

1) Alert box.

2) Confirm box.

3) Prompt box.




                  By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Dialog boxes
1) Alert box : An alert box is often used if you want to make sure information
comes through to the user. When an alert box pops up, the user will have to click
"OK" to proceed.
Syntax :             alert("some text");
Example :
<html>
           <head>
                     <script type="text/javascript">
                     function show_alert()
                     {
                               alert("Hello! I am an alert box!");
                     }
                     </script>
           </head>
           <body>
                     <input type="button" onclick="show_alert()" value="Show alert box">
           </body>
</html>
                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Dialog boxes

2) Confirm box :

           A confirm box is often used if you want the user to verify or accept

something. When a confirm box pops up, the user will have to click either

"OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true.

If the user clicks "Cancel", the box returns false.

Syntax :


           confirm("sometext");


                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Dialog boxes
<html>
          <head>
                    <script type="text/javascript">
                    function show_confirm()
                    {
                              var r=confirm("Press a button!");
                              if (r==true)
                                {
                                           alert("You pressed OK!");
                                }
                              else
                                {
                                         alert("You pressed Cancel!");
                                }
                    }
                    </script>
          </head>
          <body>
                    <input type="button" onclick="show_confirm()" value="Show a
                    confirm box" />
          </body>
</html>
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Dialog boxes
2) Prompt box :
        A prompt box is often used if you want the user to input a value
before entering a page.
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.



Syntax :
        prompt("sometext","defaultvalue");


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Dialog boxes
<html>
          <head>
                    <script type="text/javascript">
                    function show_prompt()
                    {
                              var name=prompt("Please enter your name","abc");
                              if (name!=null && name!="")
                                {
                                         document.write("Hello " + name + "! How
                                                are you today?");
                                }
                    }
                    </script>
          </head>
          <body>
                    <input type="button" onclick="show_prompt()" value="Show
                                      prompt box" />
          </body>
</html>

                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Functions
            A JavaScript function is a collection of statements, either
named or unnamed, that can be called from elsewhere within a
JavaScript program.
• To keep the browser from executing a script when the page loads, you can put
your script into a function.

• A function contains code that will be executed by an event or by a call to the
function.

• You may call a function from anywhere within a page (or even from other
pages if the function is embedded in an external .js file).

• Functions can be defined both in the <head> and in the <body> section of a
document. However, to assure that a function is read/loaded by the browser
before it is called, it could be wise to put functions in the <head> section.

                               By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Functions

Syntax of Function:

         function functionName(argument1,argument2,...,argumentX)
         {
         //statements go here;
         }




                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Functions
<html>
          <head>
                    <title>JavaScript Function</title>
                    <script type="text/javascript">
                              function displaymessage()
                              {
                              alert("Hello World!");
                              }
                    </script>
          </head>
          <body>
                    <form>
                              <input type="button" value="Click me!"
                              onclick="displaymessage()">
                    </form>
          </body>
</html>


                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Functions
The return Statement : When a function finishes executing its code, a
return value can be passed back to the caller.
Example:
         <html>
                   <head>
                             <script type="text/javascript">
                                       function multiplyNums(a,b)
                                       {
                                                 return a*b;
                                       }
                             </script>
                   </head>
                   <body>
                             <script type="text/javascript">
                                       document.write(multiplyNums(4,3));
                             </script>
                   </body>
         </html>

                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Arrays
   An array is a special variable, which can hold more than one value, at a
   time.
Defining Arrays:
1) regular array :
   e.g. var empNames=new Array(); // regular array (add an optional integer
           empNames[0]=“John";     // argument to control array's size)
           empNames[1]=“Smith";
           empNames[2]=“Mark";
2) condensed array :
   e.g. var empNames=new Array(“John",“Smith",“Mark"); // condensed array
3) literal array :
   e.g. var empNames=["John",”Smith",“Mark "]; // literal array

                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Arrays
Access an Array :


   e.g. document.write(empNames[0]);


Modify Values in an Array :


   e.g. empNames[0]=“Rajesh”;




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Controlling Flow With Loops In
                 JavaScript

In JavaScript, there are two different kind of loops:

• for - loops through a block of code a specified number
of times

• while - loops through a block of code while a
specified condition is true



                   By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Loops In JavaScript

for loops : The for loop is used when you know in advance how many times
the script should run.

Syntax :

for (variable=startvalue;variable<=endvalue;variable=variable+increment)

{

code to be executed

}




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
for Loop Example
<html>
          <body>
                    <script type="text/javascript">
                    var i=0;
                    for (i=0;i<=5;i++)
                    {
                               document.write("The number is " + i);
                               document.write("<br />");
                    }
                    </script>
                    <p>Explanation:</p>
                    <p>This for loop starts with i=0.</p>
                    <p>As long as <b>i</b> is less than, or equal to 5, the loop will
                               continue to run.</p>
                    <p><b>i</b> will increase by 1 each time the loop runs.</p>
          </body>
</html>



                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Loops In JavaScript

while loops :

           The while loop loops through a block of code while a specified condition

is true.

Syntax :

               while (variable<=endvalue)

                {

                 code to be executed

                }


                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
while Loop Example
<html>
          <body>
                    <script type="text/javascript">
                              i=0;
                              while (i<=5)
                              {
                                        document.write("The number is " + i);
                                        document.write("<br />");
                                        i++;
                              }
                    </script>
                    <p>Explanation:</p>
                    <p><b>i</b> is equal to 0.</p>
                    <p>While <b>i</b> is less than , or equal to, 5, the loop will
                    continue to run.</p>
                    <p><b>i</b> will increase by 1 each time the loop runs.</p>
          </body>
</html>

                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Loops In JavaScript

Do…while loops :            The do...while loop is a variant of the while loop. This

loop will execute the block of code ONCE, and then it will repeat the loop as long

as the specified condition is true

Syntax :

              do

               {

                code to be executed

                }

              while (variable<=endvalue);

                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Do…while Loop Example
<html>
          <body>
                    <script type="text/javascript">
                              i = 0;
                              do
                              {
                                        document.write("The number is " + i);
                                        document.write("<br />");
                                        i++;
                              }
                              while (i <= 5)
                    </script>
                    <p>Explanation:</p>
                    <p><b>i</b> equal to 0.</p>
                    <p>The loop will run</p>
                    <p><b>i</b> will increase by 1 each time the loop runs.</p>
                    <p>While <b>i</b> is less than , or equal to, 5, the loop will
                                        continue to run.</p>
          </body>
</html>

                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Break and Continue Statements
The break Statement
The break statement will break the loop and continue executing the code that
follows after the loop (if any).
Example:            <html>
                              <body>
                                        <script type="text/javascript">
                                        var i=0;
                                        for (i=0;i<=10;i++)
                                          {
                                                    if (i==3)
                                                      {
                                                              break;
                                                      }
                                          document.write("The number is " + i);
                                          document.write("<br />");
                                        }
                                        </script>
                              </body>
                    </html>
                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Break and Continue Statements
The continue statement will break the current loop and continue with the
next value.
Example: <html>
                  <body>
                            <script type="text/javascript">
                                     var i=0
                                     for (i=0;i<=10;i++)
                                      {
                                               if (i==3)
                                               {
                                                         continue;
                                               }
                                      document.write("The number is " + i);
                                      document.write("<br />");
                                      }
                            </script>
                  </body>
        </html>
                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Objects
JavaScript is a Object based Language. It allows you to define your own objects.
An object is just a special kind of data. An object has properties and methods.

• Properties :
         Properties are the values associated with an object.
e.g.     <script type="text/javascript">
                     var txt="Hello World!";
                     document.write(txt.length);
         </script>
        Output:=12
• Methods :
        Methods are the actions that can be performed on objects.
e.g.    <script type="text/javascript">
                  var str="Hello world!";
                  document.write(str.toUpperCase());
        </script>
        Output:=HELLO WORLD!



                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Type casting/
                    Data type Conversion
1) Number Conversions
2) String Conversions
3) Boolean Conversion
1) Number Conversions:
   The Number() function converts the object argument to a number that
   represents the object's value. If the value cannot be converted to a legal
   number, NaN is returned.
Syntax:
   Number(object) ;

Parameter    Description
             Optional. A JavaScript object. If no argument is provided, it
object
                returns 0.

                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Type casting
1) Number Conversion:
<html>
    <head>
         <title>Conversion to Number</title>
    </head>
    <body>
         <script type="text/javascript">
                   var test1= new Boolean(true);
                   var test2= new Boolean(false);
                   var test3= new Date();
                   var test4= new String("999");
                   var test5= new String("999 888");
                   document.write(Number(test1)+ "<br>");
                   document.write(Number(test2)+ "<br>");
                   document.write(Number(test3)+ "<br>");
                   document.write(Number(test4)+ "<br>");
                   document.write(Number(test5)+ "<br>");
         </script>
    </body>
</html>


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Note: If the parameter is a Date object, the Number() function returns the
number of milliseconds since midnight January 1, 1970 UTC.



                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Type casting/
                  Data type Conversion
2) String Conversions :



  The String() function converts the value of an object to a string.


Syntax:
               String(object);


   Parameter                           Description
   object                              Required. A JavaScript object




                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Type casting
<html>
          <head>
                    <title>Conversion to Number</title>
          </head>
          <body>
                    <script type="text/javascript">
                              var test1= new Boolean(1);
                              var test2= new Boolean(0);
                              var test3= new Boolean(true);
                              var test4= new Boolean(false);
                              var test5= new Date();
                              var test6= new String("999 888");
                              var test7=12345;
                              document.write(String(test1)+ "<br />");
                              document.write(String(test2)+ "<br />");
                              document.write(String(test3)+ "<br />");
                              document.write(String(test4)+ "<br />");
                              document.write(String(test5)+ "<br />");
                              document.write(String(test6)+ "<br />");
                              document.write(String(test7)+ "<br />");
                    </script>
          </body>
</html>
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Events

Events are actions that can be detected by JavaScript.
We define the events in the HTML tags.
Examples of events:

    •A mouse click
    •A web page or an image loading
    •Mousing over a hot spot on the web page
    •Selecting an input field in an HTML form
    •Submitting an HTML form
    •A keystroke
Note: Events are normally used in combination with functions, and the
function will not be executed before the event occurs!


                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Events

Attribute    The event occurs when...

onblur       An element loses focus
onchange     The content of a field changes
onclick      Mouse clicks an object
ondblclick   Mouse double-clicks an object
             An error occurs when loading a document or an
onerror
                image
onfocus      An element gets focus
onkeydown    A keyboard key is pressed
onkeypress   A keyboard key is pressed or held down
onkeyup      A keyboard key is released
onload       A page or image is finished loading



              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Events

Attribute     The event occurs when...


onmousedown   A mouse button is pressed

onmousemove   The mouse is moved

onmouseout    The mouse is moved off an element

onmouseover   The mouse is moved over an element

onmouseup     A mouse button is released

onresize      A window or frame is resized

onselect      Text is selected

onunload      The user exits the page


                By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Events Example
<html>
    <head>
        <script type="text/javascript">
            function upperCase()
            {
            var x=document.getElementById("fname").value
            document.getElementById("fname").value=x.toUpperCase()
            }
        </script>
    </head>
    <body>

               Enter your name:
               <input type="text" id="fname" onblur="upperCase()">

    </body>
</html>


                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
String Object:
           The String object is used to manipulate a stored piece of
text. String objects are created with new String().


Syntax :
       var txt = new String("string");
                or
       var txt = "string";


String Object Properties :
Property       Description
length         Returns the length of a string



                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Method            Description
charAt()          Returns the character at the specified index
charCodeAt()      Returns the Unicode of the character at the specified index
                  Joins two or more strings, and returns a copy of the joined
concat()
                  strings
fromCharCode()    Converts Unicode values to characters
                  Returns the position of the first found occurrence of a
indexOf()
                  specified value in a string

                  Returns the position of the last found occurrence of a
lastIndexOf()
                  specified value in a string

                  Searches for a match between a regular expression and a
match()
                  string, and returns the matches

                  Searches for a match between a substring (or regular
replace()         expression) and a string, and replaces the matched substring
                  with a new substring



                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Method          Description

                Searches for a match between a regular expression and a
search()
                string, and returns the position of the match

slice()         Extracts a part of a string and returns a new string
split()         Splits a string into an array of substrings

                Extracts the characters from a string, beginning at a specified
substr()
                start position, and through the specified number of character

                Extracts the characters from a string, between two specified
substring()
                indices

toLowerCase()   Converts a string to lowercase letters


toUpperCase()   Converts a string to uppercase letters

valueOf()       Returns the primitive value of a String object


                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects Examples

String Object:
<html>
          <head>
                    <title>String object methods</title>
          </head>
          <body>
                    <script type="text/javascript">
                             var txt="Hello World!";
                             document.write("World at "+ txt.search("World") +
                             " position <br>");
                             document.write("sliced string is "+ txt.slice(1,5) +
                             "<br>");
                             document.write(txt.split(" "));
                    </script>
          </body>
</html>



                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects Examples
String Object: To search for a specified value within a string
<html>
    <body>
          <script type="text/javascript">
              var str="Hello world!";
              document.write(str.match("world") + "<br />");
              document.write(str.match("World") + "<br />");
              document.write(str.match("worlld") + "<br />");
              document.write(str.match("world!"));
          </script>
    </body>
</html>


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects Examples
String Object:
To convert a string to lowercase or uppercase letters

<html>
   <body>

        <script type="text/javascript">

            var txt="Hello World!";
            document.write(txt.toLowerCase() + "<br />");
            document.write(txt.toUpperCase());

        </script>

    </body>
</html>

                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Date Object :
           The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date(); // current date and time
var d = new Date(milliseconds);//milliseconds since 1970/01/01
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Methods:
We can easily manipulate the date by using the methods available for the Date object.
Set Dates
In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date();
myDate.setFullYear(2010,0,14);

                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects

In the following example we set a Date object to be 5 days into the future:


var myDate=new Date();
myDate.setDate(myDate.getDate()+5);




Note: If adding five days to a date shifts the month or year, the changes are
handled automatically by the Date object itself!




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Date Object Methods
Method                     Description
getDate()                  Returns the day of the month (from 1-31)
getDay()                   Returns the day of the week (from 0-6)
getFullYear()              Returns the year (four digits)
getHours()                 Returns the hour (from 0-23)
getMilliseconds()          Returns the milliseconds (from 0-999)
getMinutes()               Returns the minutes (from 0-59)
getMonth()                 Returns the month (from 0-11)
getSeconds()               Returns the seconds (from 0-59)
getTime()                  Returns the number of milliseconds since midnight Jan 1, 1970
                           Returns the time difference between GMT and local time, in
getTimezoneOffset()
                           minutes
                           Returns the day of the month, according to universal time
getUTCDate()
                           (from 1-31)
                           Returns the day of the week, according to universal time (from
getUTCDay()
                           0-6)
getUTCFullYear()           Returns the year, according to universal time (four digits)


                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Method                   Description
getUTCHours()            Returns the hour, according to universal time (from 0-23)
                         Returns the milliseconds, according to universal time (from 0-
getUTCMilliseconds()
                         999)
getUTCMinutes()          Returns the minutes, according to universal time (from 0-59)
getUTCMonth()            Returns the month, according to universal time (from 0-11)
getUTCSeconds()          Returns the seconds, according to universal time (from 0-59)
                         Parses a date string and returns the number of milliseconds
parse()
                         since midnight of January 1, 1970
setDate()                Sets the day of the month (from 1-31)
setFullYear()            Sets the year (four digits)
setHours()               Sets the hour (from 0-23)
setMilliseconds()        Sets the milliseconds (from 0-999)
setMinutes()             Set the minutes (from 0-59)
setMonth()               Sets the month (from 0-11)
setSeconds()             Sets the seconds (from 0-59)




                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Method0-                    Description
                            Sets a date and time by adding or subtracting a specified
setTime()
                            number of milliseconds to/from midnight January 1, 1970
                            Sets the day of the month, according to universal time (from 1-
setUTCDate()
                            31)
setUTCFullYear()            Sets the year, according to universal time (four digits)
setUTCHours()               Sets the hour, according to universal time (from 0-23)
setUTCMilliseconds()        Sets the milliseconds, according to universal time (from 0-999)
setUTCMinutes()             Set the minutes, according to universal time (from 0-59)
setUTCMonth()               Sets the month, according to universal time (from 0-11)
setUTCSeconds()             Set the seconds, according to universal time (from 0-59)
setYear()                   Deprecated. Use the setFullYear() method instead
                            Converts the date portion of a Date object into a readable
toDateString()
                            string
toGMTString()               Deprecated. Use the toUTCString() method instead
                            Returns the date portion of a Date object as a string, using
toLocaleDateString()
                            locale conventions
                            Returns the time portion of a Date object as a string, using
toLocaleTimeString()
                            locale conventions
toLocaleString()            Converts a Date object to a string, using locale conventions
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Method                Description
toString()            Converts a Date object to a string
toTimeString()        Converts the time portion of a Date object to a string
toUTCString()         Converts a Date object to a string, according to universal time
                      Returns the number of milliseconds in a date string since
UTC()
                      midnight of January 1, 1970, according to universal time
valueOf()             Returns the primitive value of a Date object




                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects Examples

Date Object :

Use getFullYear() to get the year.

<html>
   <body>

         <script type="text/javascript">

         var d=new Date();
         document.write(d.getFullYear());

         </script>

    </body>
</html>
                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects Examples (Date Object )
<html>
          <head>
                    <title>Date object</title>
          </head>
          <body>
                    <script type="text/javascript">
                               var mydate= new Date();
                               var theyear=mydate.getFullYear();
                               var themonth=mydate.getMonth()+1;
                               var thetoday=mydate.getDate();
                               document.write("Today's date is: ");
                               document.write(theyear+"/"+themonth+"/"+thetoday+"<br>");
                               mydate.setFullYear(2100,0,14);
                               var today = new Date();
                               if (mydate>today)
                               {
                                         alert("Today is before 14th January 2100");
                               }
                               else
                               {
                                         alert("Today is after 14th January 2100");
                               }
                    </script>
          </body>
</html>
                              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects


Math Object :
        The Math object allows you to perform mathematical tasks.
Math is not a constructor. All properties/methods of Math can be called by
using Math as an object, without creating it.



Syntax :

          var x = Math.PI; // Returns PI
          var y = Math.sqrt(16); // Returns the square root of 16




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Math Object Properties:

Property   Description

E          Returns Euler's number (approx. 2.718)
LN2        Returns the natural logarithm of 2 (approx. 0.693)
LN10       Returns the natural logarithm of 10 (approx. 2.302)
LOG2E      Returns the base-2 logarithm of E (approx. 1.442)
LOG10E     Returns the base-10 logarithm of E (approx. 0.434)
PI         Returns PI (approx. 3.14159)
SQRT1_2    Returns the square root of 1/2 (approx. 0.707)
SQRT2      Returns the square root of 2 (approx. 1.414)


                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects
Method              Description
abs(x)              Returns the absolute value of x
acos(x)             Returns the arccosine of x, in radians
asin(x)             Returns the arcsine of x, in radians
                    Returns the arctangent of x as a numeric value between -PI/2 and PI/2
atan(x)
                    radians
atan2(y,x)          Returns the arctangent of the quotient of its arguments
ceil(x)             Returns x, rounded upwards to the nearest integer
cos(x)              Returns the cosine of x (x is in radians)
exp(x)              Returns the value of Ex
floor(x)            Returns x, rounded downwards to the nearest integer
log(x)              Returns the natural logarithm (base E) of x
max(x,y,z,...,n)    Returns the number with the highest value
min(x,y,z,...,n)    Returns the number with the lowest value
pow(x,y)            Returns the value of x to the power of y
random()            Returns a random number between 0 and 1
round(x)            Rounds x to the nearest integer
sin(x)              Returns the sine of x (x is in radians)
sqrt(x)             Returns the square root of x
tan(x)
                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
                    Returns the tangent of an angle
JavaScript Built-in Objects Examples

Math Object : properties
<html>
          <head>
                    <title>Math object properties</title>
          </head>
          <body>
                    <script type="text/javascript">
                              var x=Math.PI;
                              document.write(x);
                              document.write("<br>");
                              var y = Math.sqrt(16);
                              document.write(y);
                    </script>
          </body>
</html>




                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Built-in Objects Examples

Math Object : To use round().
<html>
    <body>

       <script type="text/javascript">

              document.write(Math.round(0.60) + "<br />");
              document.write(Math.round(0.50) + "<br />");
              document.write(Math.round(0.49) + "<br />");
              document.write(Math.round(-4.40) + "<br />");
              document.write(Math.round(-4.60));

       </script>

    </body>
</html>


                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Loops
JavaScript For...In Statement
           The for...in statement loops through the properties of an object.
Syntax :
               for (variable in object)
                {
                code to be executed
                }

e.g. <html>
           <body>
                    <script type="text/javascript">
                              var person={fname:"John",lname:"Doe",age:25};
                              for (y in person)
                              {
                                         document.write(person[y] + " ");
                              }
                    </script>
         </body>
    </html>

                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Error Handling

1) Try...Catch Statement
2) The throw Statement


1) Try...Catch Statement:
Syntax:         try
                 {
                            //Run some code here
                 }
                catch(err)
                 {
                            //Handle errors here
                 }

                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Error Handling
<html>
          <head>
                    <script type="text/javascript">
                               var txt="";
                               function message()
                               {
                                           try
                                             {
                                             adddlert("Welcome guest!");
                                             }
                                           catch(err)
                                             {
                                             txt="There was an error on this page.nn";
                                             txt+="Error description: " + err.description + "nn";
                                             txt+="Click OK to continue.nn";
                                             alert(txt);
                                             }
                               }
                    </script>
          </head>
          <body>
                    <input type="button" value="View message" onclick="message()" />
          </body>
</html>


                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Error Handling

2) The throw Statement :

          The throw statement allows you to create an exception. If you

  use this statement together with the try...catch statement, you can

  control program flow and generate accurate error messages.



Syntax:

                  throw exception ;




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Error Handling
<html>
    <body>
       <script type="text/javascript">
           var x=prompt("Enter a number between 0 and 10:","");
           try
             {
                 if(x>10)
                   {
                   throw "Err1";
                   }
                 else if(x<0)
                   {
                   throw "Err2";
                   }
                 else if(isNaN(x))
                   {
                   throw "Err3";
                   }
             }

                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Error Handling
              catch(er)
                {
                     if(er=="Err1")
                       {
                       alert("Error! The value is too high");
                       }
                     if(er=="Err2")
                       {
                       alert("Error! The value is too low");
                       }
                     if(er=="Err3")
                       {
                       alert("Error! The value is not a number");
                       }
                   }
          </script>
          </body>
</html>


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
The Document Object Model and Browser Hierarchy :




                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Document Tree Structure
document


document.
documentElement

document.body




                  By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
child, sibling, parent




              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
child, sibling, parent




              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
child, sibling, parent




              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
child, sibling, parent




              By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Working with frames
frameset.html:


<HTML>
      <HEAD>
         <TITLE>Frames Values</TITLE>
      </HEAD>
      <FRAMESET cols="20%,80%">
         <FRAME SRC="jex13.html" name="left_frame">
         <FRAME SRC="jex14.html" name="right_frame">
      </FRAMESET>
</HTML>




                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Working with frames
jex14.html:


<HTML>
      <HEAD>
         <TITLE>JavaScript Example 14</TITLE>
      </HEAD>
      <BODY>
         <FORM name="form1">
         <INPUT type="text" name="text1" size="25" value="">
         </FORM>
      </BODY>
</HTML>



                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Working with frames
jex13.htm:
<HTML>
             <HEAD>
                    <TITLE>JavaScript Example 13</TITLE>
            </HEAD>
            <BODY>
            <FORM>
                    <INPUT type="button" value="What is
    course name?"
    onClick="parent.right_frame.document.form1.text1.value='
    MCA!'">
            </FORM>
            </BODY>
</HTML>




             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Document Object

Document Object Collections :

Collection   Description


anchors[ ]   Returns an array of all the anchors in the document
forms[ ]     Returns an array of all the forms in the document
images[ ]    Returns an array of all the images in the document
links[ ]     Returns an array of all the links in the document




                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Document Object Properties
Property       Description

               Returns all name/value pairs of cookies in the
cookie
               document
               Returns the mode used by the browser to render the
documentMode
               document
               Returns the domain name of the server that loaded the
domain
               document
               Returns the date and time the document was last
lastModified
               modified
readyState     Returns the (loading) status of the document
               Returns the URL of the document that loaded the
referrer
               current document
title          Sets or returns the title of the document
URL            Returns the full URL of the document

                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Document Object Methods
Method                   Description

                         Closes the output stream previously opened
close()
                         with document.open()

getElementById()         Accesses the first element with the specified id

getElementsByName()      Accesses all elements with a specified name

                         Accesses all elements with a specified
getElementsByTagName()
                         tagname
                         Opens an output stream to collect the output
open()
                         from document.write() or document.writeln()
                         Writes HTML expressions or JavaScript code
write()
                         to a document
                         Same as write(), but adds a newline character
writeln()
                         after each statement



                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms, elements and events

•The Form object represents an HTML form.
•For each <form> tag in an HTML document, a Form object is created.
•Forms are used to collect user input, and contain input elements like
text fields, checkboxes, radio-buttons, submit buttons and more.

•A form can also contain select menus, textarea, fieldset, and label
elements.

•Forms are used to pass data to a server.
•Form Object Collections :
Collection     Description
elements[ ]    Returns an array of all elements in a form



                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms, elements and events
Form Object Properties :

Property        Description


                Sets or returns the value of the accept-charset attribute
acceptCharset
                in a form
action          Sets or returns the value of the action attribute in a form
                Sets or returns the value of the enctype attribute in a
enctype
                form
length          Returns the number of elements in a form
                Sets or returns the value of the method attribute in a
method
                form
name            Sets or returns the value of the name attribute in a form
target          Sets or returns the value of the target attribute in a form

                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms, elements and events


          Form Object Methods :


Method              Description

reset()             Resets a form
submit()            Submits a form




                 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms, elements and events



           Form Object Events :


Event        The event occurs when...
onreset      The reset button is clicked
onsubmit     The submit button is clicked




               By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms, elements and events
<html>
 <body>
  <form id="frm1">
        First name: <input type="text“ name="fname" value="Donald" /><br />
        Last name: <input type="text" name="lname" value="Duck" /><br />
        <input type="submit" value="Submit" />
  </form>
  <p>Return the value of each element in the form:</p>
  <script type="text/javascript">
        var x=document.getElementById("frm1");
        for (var i=0;i<x.length;i++)
          {
                   document.write(x.elements[i].value);
                   document.write("<br />");
          }
  </script>
 </body>
</html>


                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms Methods reset()
<html>
    <head>
        <script type="text/javascript">
        function formReset()
        {
        document.getElementById("frm1").reset();
        }
        </script>
    </head>
    <body>

       <form id="frm1">
           First name: <input type="text" name="fname" /><br />
           Last name: <input type="text" name="lname" /><br />
           <input type="button" onclick="formReset()" value="Reset form" />
       </form>

    </body>
</html>

                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms Methods submit()
<html>
    <head>
        <script type="text/javascript">
        function formSubmit()
        {
        document.getElementById("frm1").submit();
        }
        </script>
    </head>
    <body>
        <p>Enter some text in the fields below, then press the "Submit
        form" button to submit the form.</p>
        <form id="frm1" method="get">
            First name: <input type="text" name="fname" /><br />
            Last name: <input type="text" name="lname" /><br /><br />
            <input type="button" onclick="formSubmit()" value="Submit
            form" />
        </form>
    </body>
</html>
                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms Event (onreset)
<html>
   <body>
          <p>Enter some text in the fields below, then press the Reset button
          to reset the form.</p>
          <form onreset="alert('The form will be reset')">
          Firstname: <input type="text" name="fname" value="First" /><br />
          Lastname: <input type="text" name="lname" value="Last" />
          <br /><br />
          <input type="reset" value="Reset" />
          </form>
   </body>
</html>


                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Forms Event (onsubmit)
<html>
    <head>

       <script type="text/javascript">
       function greeting()
       {
       alert("Welcome " + document.forms["frm1"]["fname"].value + "!")
       }
       </script>

    </head>
    <body>
        What is your name?<br />
        <form name="frm1" action="submit.htm" onsubmit="greeting()">
            <input type="text" name="fname" />
            <input type="submit" value="Submit" />
        </form>
        </body>
</html>

                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Definition:
           A string that is used to describe or match a set of strings, according
to certain syntax.
           Regular expressions are used to perform powerful pattern-matching
and "search-and-replace" functions on text.
Syntax :
                   var patt=new RegExp(pattern,modifiers);
                            or more simply:
                   var patt=/pattern/modifiers;


•pattern specifies the pattern of an expression
•modifiers specify if a search should be global, case-sensitive, etc.
                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression


    Modifiers
    Modifiers are used to perform case-insensitive and global searches:


Modifier          Description

i                 Perform case-insensitive matching

                  Perform a global match (find all matches rather than
g
                     stopping after the first match)




                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Modifier i:
   <html>
      <body>
       <script type="text/javascript">
                var str = "Visit Siberindia";
                var patt1 = /Siberindia/i;
                document.write(str.match(patt1));
       </script>
      </body>
   </html>

                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Modifier g:
   <html>
     <body>
      <script type="text/javascript">
              var str="Is this all there is?";
              var patt1=/is/g;
              document.write(str.match(patt1));
      </script>
     </body>
   </html>

                     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Modifier g and i:


   <html>
     <body>
      <script type="text/javascript">
               var str="Is this all there is?";
               var patt1=/is/gi;
               document.write(str.match(patt1));
      </script>
     </body>
   </html>

                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Methods


Method         Description


exec()         Tests for a match in a string. Returns the first match



test()         Tests for a match in a string. Returns true or false



compile()      Compiles a regular expression




                      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Methods
test() :
  The test() method searches a string for a specified value, and returns true
  or false, depending on the result.
Example:
<html>
  <body>
          <script type="text/javascript">
                  var patt1=new RegExp("e");
                  document.write(patt1.test("The best things in life
                  are free"));
          </script>
  </body>
</html>
                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Methods
exec() :
  The exec() method searches a string for a specified value, and returns the
  text of the found value. If no match is found, it returns null.
Example:
   <html>
      <body>
       <script type="text/javascript">
                var patt1=new RegExp("e");
                document.write(patt1.exec("The best things in life
                         are free"));
       </script>
      </body>
   </html>
                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Methods
compile() : The compile() method is used to compile a regular
  expression during execution of a script. The compile() method can also
  be used to change and recompile a regular expression.
Example:
   <html>
      <body>
      <script>
      var str="Every man in the world! Every woman on earth!";
      var patt=/man/g;
      var str2=str.replace(patt,"person");
      document.write(str2+"<br />");
      patt=/(wo)?man/g;
      patt.compile(patt);
      str2=str.replace(patt,"person");
      document.write(str2);
      </script>
      </body>
   </html>
                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Brackets :
Brackets are used to find a range of characters

Expression          Description
[abc]               Find any character between the brackets
[^abc]              Find any character not between the brackets
[0-9]               Find any digit from 0 to 9
[A-Z]               Find any character from uppercase A to uppercase Z
[a-z]               Find any character from lowercase a to lowercase z
[A-z]               Find any character from uppercase A to lowercase z
[adgk]              Find any character in the given set
[^adgk]             Find any character outside the given set
(red|blue|green)    Find any of the alternatives specified

                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression

<html>

          <body>

                    <script type="text/javascript">

                            var str="Is this all there is?";

                            var patt1=/[a-h]/g;

                            document.write(str.match(patt1));

                    </script>

          </body>

</html>

                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression




      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Metacharacters :Metacharacters are characters with a special meaning:

Metacharacter Description

.              Find a single character, except newline or line terminator
w             Find a word character
W             Find a non-word character
d             Find a digit
D             Find a non-digit character
s             Find a whitespace character
S             Find a non-whitespace character
b             Find a match at the beginning/end of a word
B             Find a match not at the beginning/end of a word
0             Find a NUL character



                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
Metacharacters :Metacharacters are characters with a special meaning:

Metacharacter       Description

n                  Find a new line character
f                  Find a form feed character
r                  Find a carriage return character
t                  Find a tab character
v                  Find a vertical tab character
                    Find the character specified by an octal
xxx
                    number xxx
                    Find the character specified by a hexadecimal
xdd
                    number dd
                    Find the Unicode character specified by a
uxxxx
                    hexadecimal number xxxx

                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression
<html>
   <body>
        <script type="text/javascript">
                 var str="This is my car!";
                 var patt1=/c.r/g;
                 document.write(str.match(patt1));
        </script>
   </body>
</html>




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Properties


Property     Description



global       Specifies if the "g" modifier is set


ignoreCase   Specifies if the "i" modifier is set


lastIndex    The index at which to start the next match


source       The text of the RegExp pattern




                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Properties
<html>
          <body>
                 <script type="text/javascript">
                         var str="The rain in Spain stays mainly in
                                 the plain";
                         var patt1=/ain/g;
                         while (patt1.test(str)==true)
                          {
                                  document.write("'ain' found.
                                 Index now at: "+patt1.lastIndex);
                                  document.write("<br />");
                          }
                 </script>
          </body>
</html>



                       By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Regular Expression Properties




            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation

      JavaScript can be used to validate data in
HTML forms before sending off the content to a
server.
Form data that typically are checked by a JavaScript
could be:

•has the user left required fields empty?
•has the user entered a valid e-mail address?
•has the user entered a valid date?
•has the user entered text in a numeric field?
                 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation (Required Fields)
<html>
          <head>
                    <script type="text/javascript">
                    function validateForm()
                    {
                              var x=document.forms["myForm"]["fname"].value
                              if (x==null || x=="")
                                {
                                          alert("First name must be filled out");
                                          return false;
                                }
                    }
                    </script>
          </head>
          <body>
                    <form name="myForm"
                    action="http://localhost/myweb/test1.asp"
                    onsubmit="return validateForm()" method="post">
                    First name: <input type="text" name="fname">
                    <input type="submit" value="Submit">
                    </form>
          </body>
</html>
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Cookies

cookie: a small amount of information sent by a server to a
browser, and then sent back by the browser on future page
requests.


cookies have many uses:
   •authentication
   •user tracking
   •maintaining user preferences, shopping carts, etc.
       A cookie's data consists of a single name/value pair,
sent in the header of the client's HTTP GET or POST request


                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Cookies

How cookies are sent
1) when the browser requests a page, the server may
send back a cookie(s) with it
2) if your server has previously sent any cookies to
the browser, the browser will send them back on
subsequent requests
alternate model: client-side JavaScript code can
set/get



                 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Cookies

Myths:

  •Cookies are like worms/viruses and can erase
  data from the user's hard disk.

  •Cookies are a form of spyware and can steal
  your personal information.

  •Cookies generate popups and spam.
  •Cookies are only used for advertising.
                By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Cookies

Facts:

•Cookies are only data, not program code.
•Cookies cannot erase or read information from
the user's computer.

•Cookies are usually anonymous (do not contain
personal information).

•Cookies CAN be used to track your viewing
habits on a particular site. A. Bhosale. Assistant Professor, SIBER
              By Mrs. Geetanjali
JavaScript Cookies
How long does a cookie exist?
session cookie : the default type; a temporary cookie that is
stored only in the browser's memory
    when the browser is closed, temporary cookies will be
    erased
    can not be used for tracking long-term information
    safer, because no programs other than the browser can
    access them
persistent cookie : one that is stored in a file on the
browser's computer
    can track long-term information
    potentially less secure, because users (or programs
    they run) can By Mrs.cookie files,Bhosale. Assistant Professor, SIBER
                  open Geetanjali A. see/change the cookie
JavaScript Cookies
Examples of cookies:
1) Name cookie - The first time a visitor arrives to your web page,
he or she must fill in her/his name. The name is then stored in a
cookie. Next time the visitor arrives at your page, he or she could
get a welcome message like "Welcome John Doe!" The name is
retrieved from the stored cookie
2) Password cookie - The first time a visitor arrives to your web
page, he or she must fill in a password. The password is then
stored in a cookie. Next time the visitor arrives at your page, the
password is retrieved from the cookie
3) Date cookie - The first time a visitor arrives to your web page,
the current date is stored in a cookie. Next time the visitor arrives
at your page, he or she could get a message like "Your last visit
was on Tuesday August 11, 2005!" The date is retrieved from the
                By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Cookies
Stateless
• When stateless protocol is used between a server and the client, the
server does not remember anything.
• It treats any message from a client as the client's first message and
responds with the same effects every time.
• Stateless means there is no record of previous interactions and each
interaction request has to be handled based entirely on information that
comes with it.
• Example : http
Stateful
• Stateful protocol means the server remembers what a client has done
before.
• The computer or program keeps track of the state of interaction, usually
by setting values in a storage field designated for that purpose.
• Example: FTP, Telnet

                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation (Numeric value)
<html>
 <head>
   <title>Numeric TextBox</title>
   <script lanugage="javascript">
    function test()
   {
     var value=document.form1.t.value;
     var ch,i;
     for(i=0;i<value.length;i++)
     {
           ch=value.charAt(i);
            if (ch >= "0" && ch <="9")
              continue;
            else
            {
             alert("Non-numeric character is not allowed...");
             break;
            }
     }
   }
   </script>
 </head>

                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation (Numeric value)
  <body>
    <form name="form1">
         <input type="text" name="t" onChange="test();">
    </form>
 </body>
</html>




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation (accept                       4 digit code)
<html>
<head>
<title>Regex in JavaScript</title>
<script language="JavaScript“>
function validate(code)
{
     var fourDigitCode = /^([a-zA-Z0-9]{4})$/;
     var status = document.getElementById("status");
     if(fourDigitCode.test(code) == false)
     {
          status.innerHTML = "Enter a four digit code.“;
     }
     else
     {
          status.innerHTML = "Success!";
     }
}
</script>




                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation (accept                      4 digit code)
<style type="text/css">
<!--
div {
width: 100%;
text-align: center;
margin-top:150px;
}
span {
color: #000099;
font: 8pt verdana;
font-weight:bold;
text-decoration:none;
}
input {
color: #000000;
background: #F8F8F8;
border: 1px solid #353535;
width:250px;
font: 8pt verdana;
font-weight:normal;
text-decoration:none;
margin-top:5px;
}
-->                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
</style>
JavaScript Form Validation (accept                       4 digit code)
</head>
<body>

<div>
<span id="status">Enter a four digit code.</span><br>
<input type="text" name="code" onkeyup="validate(this.value);">
</div>
</body>
</html>




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Form Validation (number Validation)
<html>
 <head>
   <title>Numeric TextBox</title>
   <script type='text/javascript'>
                      function isNumeric(elem, helperMsg)
                      {
                                  var numericExpression = /^[0-9]+$/;
                                  if(elem.value.match(numericExpression))
                                  {
                                             return true;
                                  }
                                  else
                                  {
                                             alert(helperMsg);
                                             elem.focus();
                                             return false;
                                  }
                      }
           </script>
 </head>
 <body>
           <form>
                      Numbers Only: <input type='text' id='numbers'/>
                      <input type='button'
                                  onclick="isNumeric(document.getElementById('numbers'),
                                  'Numbers Only Please')"
                                  By Mrs. Geetanjali A. Bhosale. Assistant Professor,
                                  value='Check Field' />                                   SIBER
           </form> </body></html>
JavaScript Objects
Creating Your Own Objects :
1. Create a direct instance of an object
   personObj=new Object();
   personObj.firstname="John";
   personObj.lastname="Doe";
   personObj.age=50;
   personObj.eyecolor="blue";
                  OR
personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
You can call a method with the following syntax:
   objName.methodName()
e.g.     personObj.sleep();


                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Objects
Creating Your Own Objects :
2. Create an object constructor
   function person(firstname,lastname,age,eyecolor)
   {
   this.firstname=firstname;
   this.lastname=lastname;
   this.age=age;
   this.eyecolor=eyecolor;
   }
Once you have the object constructor, you can create new instances of the object,
   like this:
   var myFather=new person("John","Doe",50,"blue");
   var myMother=new person("Sally","Rally",48,"green");
                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Objects
You can also add some methods to the person object. This is also done inside the
   function:
       function person(firstname,lastname,age,eyecolor)
         {
         this.firstname=firstname;
         this.lastname=lastname;
         this.age=age;
         this.eyecolor=eyecolor;

         this.newlastname=newlastname;
         }

Note that methods are just functions attached to objects. Then we will have to write
   the newlastname() function:

   function newlastname(new_lastname)
        {
        this.lastname=new_lastname;
        }

                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Strengths and weaknesses
Strengths of JavaScript
   JavaScript offers several strengths to the programmer including a short
   development cycle, ease-of-learning, and small size scripts. These strengths
   mean that JavaScript can be easily and quickly used to extend HTML pages
   already on the Web.
1) Quick Development
   Because JavaScript does not require time-consuming compilation, scripts can
   be developed in a relatively short period of time. This is enhanced by the fact
   that most of the interface features, such as dialog boxes, forms, and other GUI
   elements, are handled by the browser and HTML code. JavaScript
   programmers don't have to worry about creating or handling these elements of
   their applications.
2) Easy to Learn
   While JavaScript may share many similarities with Java, it doesn't include the
   complex syntax and rules of Java. By learning just a few commands and simple
   rules of syntax, along with understanding the way objects are used in
   JavaScript, it is possible to begin creating fairly sophisticated programs.
                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Strengths and weaknesses
.
3) Platform Independence

  Because the World Wide Web, by its very nature, is platform-independent,
  JavaScript programs created for Netscape Navigator are not tied to any specific
  hardware platform or operating system. The same program code can be used
  on any platform for which Navigator 2.0 is available.

4) Small Overhead

  JavaScript programs tend to be fairly compact and are quite small, compared to
  the binary applets produced by Java. This minimizes storage requirements on
  the server and download times for the user. In addition, because JavaScript
  programs usually are included in the same file as the HTML code for a page,
  they require fewer separate network accesses.


                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Strengths and weaknesses
Weaknesses of JavaScript
   As would be expected, JavaScript also has its own unique weaknesses. These
   include a limited set of built-in methods, the inability to protect source code from
   prying eyes, and the fact that JavaScript still doesn't have a mature
   development and debugging environment.
1. Limited Range of Built-In Methods
   Early versions of the Navigator 2.0 beta included a version of JavaScript that
   was rather limited. In the final release of Navigator 2, the number of built-in
   methods had significantly increased, but still didn't include a complete set of
   methods to work with documents and the client windows. With the release of
   Navigator 3, things have taken a further step forward with the addition of
   numerous methods, properties, and event handlers.
2. No Code Hiding :Because the source code of JavaScript script presently must
   be included as part of the HTML source code for a document, there is no way to
   protect code from being copied and reused by people who view your Web
   pages. This raises concerns in the software industry about protection of
   intellectual property. The consensus is that JavaScript scripts are basically
   freeware at this point in By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
                             time.
JavaScript Strengths and weaknesses
3. Lack of Debugging and Development Tools
   Most well-developed programming environments include a suite of tools that
   make development easier and simplify and speed up the debugging process.
   Currently, there are some HTML editors and programming editors that provide
   JavaScript support. In addition, there are some on-line tools for debugging and
   testing JavaScript scripts. However, there are really no integrated development
   environments such as those available for Java, C, or C++. LiveWire from
   Netscape provides some development features but is not a complete
   development environment for client-side JavaScript.




                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects




• Window
• Navigator
• Screen
• History
• Location


     By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects

• Window:
          The window object represents an open window in a browser.
    If a document contain frames (<frame> or <iframe> tags), the
          browser creates one window object for the HTML document, and
          one additional window object for each frame.
    Window Object Properties:
Property          Description
                  Returns a Boolean value indicating whether a window has been closed or
closed
                  not
defaultStatus     Sets or returns the default text in the statusbar of a window
document          Returns the Document object for the window
                  Returns an array of all the frames (including iframes) in the current
frames
                  window
history           Returns the History object for the window
innerHeight       Sets or returns the inner height of a window's content area


                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
Property      Description
innerWidth    Sets or returns the inner width of a window's content area
length        Returns the number of frames (including iframes) in a window
location      Returns the Location object for the window
name          Sets or returns the name of a window
navigator     Returns the Navigator object for the window
opener        Returns a reference to the window that created the window
outerHeight   Sets or returns the outer height of a window, including toolbars/scrollbars
outerWidth    Sets or returns the outer width of a window, including toolbars/scrollbars
              Returns the pixels the current document has been scrolled (horizontally)
pageXOffset
              from the upper left corner of the window
              Returns the pixels the current document has been scrolled (vertically)
pageYOffset
              from the upper left corner of the window
parent        Returns the parent window of the current window
screen        Returns the Screen object for the window
screenLeft    Returns the x coordinate of the window relative to the screen
screenTop     Returns the y coordinate of the window relative to the screen
screenX       Returns the x coordinate of the window relative to the screen
screenY       Returns the y coordinate of the window relative to the screen
self          Returns the current window
status        Sets the text in the statusbar of a window
top
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
              Returns the topmost browser window
JavaScript Browser Objects (Window)

<html>
         <head>
                  <script type="text/javascript">
                            var myWindow;

                           function openWin()
                           {
                           myWindow=window.open("","","width=400,height=200");
                           }

                           function closeWin()
                           {
                                    if (myWindow)
                                    {
                                      myWindow.close();
                                    }
                           }


                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
function checkWin()
{
         if (!myWindow)
         {
                    document.getElementById("msg").innerHTML="'myWindow' has
                  never been opened!";
         }
         else
         {
                  if (myWindow.closed)
                  {
                     document.getElementById("msg").innerHTML="'myWindow' has
                           been closed!";
                  }
                  else
                  {
                      document.getElementById("msg").innerHTML="'myWindow' has
                           not been closed!";
                  }
         }
}                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
</script>
</head>
<body>
         <input type="button" value="Open 'myWindow'" onclick="openWin()" />
         <input type="button" value="Close 'myWindow'" onclick="closeWin()" />
         <br /><br />
         <input type="button" value="Has 'myWindow' been closed?"
onclick="checkWin()" />
         <br /><br />
         <div id="msg"></div>
</body>
</html>




                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
<html>
          <head>
                   <script type="text/javascript">
                   function openWin()
                   {
                   myWindow=window.open('','');
                   myWindow.innerHeight=“200";
                   myWindow.innerWidth=“200";
                   myWindow.document.write("<p>This is 'myWindow'</p>");
                   myWindow.focus();
                   }
                   </script>
          </head>
          <body>
          <input type="button" value="Open 'myWindow'" onclick="openWin()" />
          </body>
</html>

Note:The innerHeight and innerWidth properties only works in Firefox.

                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
   Window Object Methods:
Method            Description

alert()           Displays an alert box with a message and an OK button

blur()            Removes focus from the current window

clearInterval()   Clears a timer set with setInterval()

clearTimeout()    Clears a timer set with setTimeout()

close()           Closes the current window

confirm()         Displays a dialog box with a message and an OK and a Cancel button

createPopup()     Creates a pop-up window

focus()           Sets focus to the current window

moveBy()          Moves a window relative to its current position

moveTo()          Moves a window to the specified position

open()            Opens a new browser window

print()           Prints the content of the current window



                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
  Window Object Methods:

Method             Description

prompt()           Displays a dialog box that prompts the visitor for input

resizeBy()         Resizes the window by the specified pixels

resizeTo()         Resizes the window to the specified width and height

scrollBy()         Scrolls the content by the specified number of pixels

scrollTo()         Scrolls the content to the specified coordinates

                   Calls a function or evaluates an expression at specified intervals (in
setInterval()
                   milliseconds)


                   Calls a function or evaluates an expression after a specified number of
setTimeout()
                   milliseconds




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
popupwin.html (program for createPopup() method)

<html>
     <head>
         <script type="text/javascript">
              function show_popup()
              {
              var p=window.createPopup();
              var pbody=p.document.body;
              pbody.style.backgroundColor="lime";
              pbody.style.border="solid black 1px";
              pbody.innerHTML="This is a pop-up! Click outside the pop-up to close.";
              p.show(150,150,200,50,document.body);
              }
         </script>
     </head>
     <body>
         <button onclick="show_popup()">Show pop-up!</button>
         <p><b>Note:</b> The createPopup() method only works in IE!</p>
     </body>
</html>


                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
winblur.html (program for blur() method)
<html>
    <head>
        <script type="text/javascript">
        function openWin()
        {
        myWindow=window.open('','','width=200,height=100');
        myWindow.document.write("<p>This is 'myWindow'</p>");
        myWindow.blur();
        }
        </script>
    </head>
    <body>

   <input type="button" value="Open window" onclick="openWin()" />

    </body>
</html>


                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
Window open() Method :
Syntax:
        window.open(URL,name,specs,replace)
 Parameter   Description
             Optional. Specifies the URL of the page to open. If no URL is specified, a new
 URL
             window with about:blank is opened

             Optional. Specifies the target attribute or the name of the window. The following
             values are supported:
             •_blank - URL is loaded into a new window. This is default
 name        •_parent - URL is loaded into the parent frame
             •_self - URL replaces the current page
             •_top - URL replaces any framesets that may be loaded
             •name - The name of the window


 specs       Optional. A comma-separated list of items.

             Optional.Specifies whether the URL creates a new entry or replaces the current
             entry in the history list. The following values are supported:
   replace   •true - URL replaces the current document in the history list
             •false - URL creates a new entry in the history list




                             By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
specs
                         Whether or not to display the window in theater mode. Default is no. IE
channelmode=yes|no|1|0
                         only
directories=yes|no|1|0   Whether or not to add directory buttons. Default is yes. IE only
                         Whether or not to display the browser in full-screen mode. Default is no.
fullscreen=yes|no|1|0
                         A window in full-screen mode must also be in theater mode. IE only
height=pixels            The height of the window. Min. value is 100
left=pixels              The left position of the window
location=yes|no|1|0      Whether or not to display the address field. Default is yes
menubar=yes|no|1|0       Whether or not to display the menu bar. Default is yes
resizable=yes|no|1|0     Whether or not the window is resizable. Default is yes
scrollbars=yes|no|1|0    Whether or not to display scroll bars. Default is yes
status=yes|no|1|0        Whether or not to add a status bar. Default is yes
                         Whether or not to display the title bar. Ignored unless the calling
titlebar=yes|no|1|0
                         application is an HTML Application or a trusted dialog box. Default is yes
toolbar=yes|no|1|0       Whether or not to display the browser toolbar. Default is yes
top=pixels               The top position of the window. IE only
width=pixels


                               By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Window)
customalert.html
<html>
 <head>
   <title>Custom Alert</title>
   <script language="javascript">
     function makeAlert(height,width,message)
     {
        var win=window.open("","","height="+height+",width="+width);
        win.document.open();
        var text="";
        text+="<html><head><title>Alert</title></head><body bgcolor='#ffffff'>";
        text+=message + "<form><center>";
        text+="<input type=button value=' OK ' onClick='self.close();' ";
        text+="<</center></form></body></html>";
        win.document.write(text);
        win.document.close();
     }
   </script>
 </head>
 <body>
  <form>
      <input type="button" value="Make an Alert" onClick="makeAlert(85,200,'<center>This is a
custom Alert! </center>')">
  </form>
 </body>
</html>
                                By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (History)
History Object:
          The history object contains the URLs visited by the user (within a
browser window).
The history object is part of the window object and is accessed through the
window.history property.


History Object Properties :

Property      Description
  length                 Returns the number of URLs in the history list

Syntax:
           history.length
Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1.


                               By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (History)


<html>
    <body>

       <script type="text/javascript">
       document.write("Number of URLs in history list: " + history.length);
       </script>

    </body>
</html>




                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (History)



                History Object Methods :

Method          Description
back()          Loads the previous URL in the history list
forward()       Loads the next URL in the history list
go()            Loads a specific URL from the history list




                   By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (History)
historyBack.html

<html>
    <head>
        <script type="text/javascript">
            function goBack()
              {
              window.history.back()
              }
        </script>
    </head>
    <body>

        <input type="button" value="Back" onclick="goBack()" />

        <p>Notice that clicking on the Back button here will not result in any
        action, because there is no previous URL in the history list.</p>

    </body>
</html>
                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Location)
Location Object :
The location object contains information about the current URL.
The location object is part of the window object and is accessed through the
window.location property.
Location Object Properties :
 Property     Description
 hash         Returns the anchor portion of a URL
 host         Returns the hostname and port of a URL
 hostname     Returns the hostname of a URL
 href         Returns the entire URL
 pathname     Returns the path name of a URL
 port         Returns the port number the server uses for a URL
 protocol     Returns the protocol of a URL
 search       Returns the query portion of a URL

                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Location)

<html>
          <head>
                    <title>Location Object</title>
          </head>
          <body>
                    <script type="text/javascript">
                             document.write(location.hash);
                             document.write(location.host);
                             document.write(location.hostname);
                             document.write(location.href);
                             document.write(location.pathname);
                             document.write(location.port);
                             document.write(location.protocol);
                             document.write(location.search);
                    </script>
          </body>
</html>

                           By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Location)
Location Object Methods :



Method      Description

assign()    Loads a new document

reload()    Reloads the current document

replace()   Replaces the current document with a new one




                   By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Location)

<html>
          <head>
                    <script type="text/javascript">
                    function newDoc()
                    {
                    window.location.assign("http://www.google.com")
                    }
                    </script>
          </head>
          <body>
                    <input type="button" value="Load new document"
                             onclick="newDoc()" />
          </body>
</html>




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Location)
<html>
          <head>
                    <script type="text/javascript">
                            function reloadPage()
                            {
                                window.location.reload()
                            }
                    </script>
          </head>
          <body>
                    <input type="button" value="Reload page“
          onclick="reloadPage()" />
          </body>
</html>
                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Location)

<html>
          <head>
                    <script type="text/javascript">
                    function replaceDoc()
                    {
                    window.location.replace("http://www.google.com")
                    }
                    </script>
          </head>
          <body>
                    <input type="button" value="Replace document"
                    onclick="replaceDoc()" />
          </body>
</html>




                          By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Detection
The Navigator Object:
The Navigator object contains all information about the visitor's browser:

 Navigator Object Properties :

Property             Description
appCodeName          Returns the code name of the browser
appName              Returns the name of the browser
appVersion           Returns the version information of the browser

                     Determines whether cookies are enabled in the
cookieEnabled
                     browser

platform             Returns for which platform the browser is compiled

                     Returns the user-agent header sent by the browser
userAgent
                     to the server

                        By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Detection
Navigator Object Methods

Method           Description
                 Specifies whether or not the browser has Java
javaEnabled()
                 enabled
                 Specifies whether or not the browser has data
taintEnabled()
                 tainting enabled




                    By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Detection
<html>
<body>
<div id="example"></div>
<script type="text/javascript">
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
</body>
</html>
                         By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Detection




      By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
JavaScript Browser Objects (Screen)
The screen object contains information about the visitor's screen.

Screen Object Properties:
Property      Description

availHeight   Returns the height of the screen (excluding the Windows Taskbar)

availWidth    Returns the width of the screen (excluding the Windows Taskbar)

colorDepth    Returns the bit depth of the color palette for displaying images

height        Returns the total height of the screen

pixelDepth    Returns the color resolution (in bits per pixel) of the screen

width         Returns the total width of the screen




                            By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER

More Related Content

PDF
PPTX
Java script
PDF
Javascript essentials
PPTX
Java script
PPTX
JavaScript New Tutorial Class XI and XII.pptx
PPTX
Java script
PDF
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
PPTX
Java script
Java script
Javascript essentials
Java script
JavaScript New Tutorial Class XI and XII.pptx
Java script
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
Java script

What's hot (20)

PPTX
PPT
Java Basics
PPTX
Javascript
PPTX
HTML (Web) basics for a beginner
PPT
Js ppt
PDF
A Basic Django Introduction
PDF
JavaScript - Chapter 10 - Strings and Arrays
PPTX
Angular 14.pptx
PDF
jQuery for beginners
PPTX
JavaScript Basic
PDF
JavaScript Programming
PDF
JavaScript - Chapter 11 - Events
PPTX
Django Girls Tutorial
PPTX
Hibernate ppt
PPT
Jsp ppt
PPT
Java script final presentation
PPTX
Lab #2: Introduction to Javascript
PPT
Advanced Javascript
PPTX
Object Oriented Programming In JavaScript
Java Basics
Javascript
HTML (Web) basics for a beginner
Js ppt
A Basic Django Introduction
JavaScript - Chapter 10 - Strings and Arrays
Angular 14.pptx
jQuery for beginners
JavaScript Basic
JavaScript Programming
JavaScript - Chapter 11 - Events
Django Girls Tutorial
Hibernate ppt
Jsp ppt
Java script final presentation
Lab #2: Introduction to Javascript
Advanced Javascript
Object Oriented Programming In JavaScript
Ad

Viewers also liked (20)

PPT
Print CSS
PPT
Ecommerce final
PDF
Javascript (parte 1)
PPT
Powsys may2008
PPTX
Bourne supremacy
PPT
Ieee Meeting Anacapri
PPT
Public final
PDF
Django Bogotá. CBV
PPT
Questionnaire Results
PPTX
Media question 2
PPT
Maiadia Company Profile In Brief V03
PPTX
Distribution
PPT
Questionnaire Presentation
PDF
The agar wood industry yet to utilize in bangladesh
PPTX
Pos daya
PPTX
Burton's theory
PDF
An Analysis of SAFTA in the Context of Bangladesh
PPTX
Javascript - Array - Creating Array
PPT
Javascript arrays
PDF
The Bangladeshi Agarwood Industry: Development Barriers and a Potential Way...
Print CSS
Ecommerce final
Javascript (parte 1)
Powsys may2008
Bourne supremacy
Ieee Meeting Anacapri
Public final
Django Bogotá. CBV
Questionnaire Results
Media question 2
Maiadia Company Profile In Brief V03
Distribution
Questionnaire Presentation
The agar wood industry yet to utilize in bangladesh
Pos daya
Burton's theory
An Analysis of SAFTA in the Context of Bangladesh
Javascript - Array - Creating Array
Javascript arrays
The Bangladeshi Agarwood Industry: Development Barriers and a Potential Way...
Ad

Similar to Javascript by geetanjali (20)

DOC
Java script by Act Academy
DOC
2javascript web programming with JAVA script
PDF
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
PDF
Web programming UNIT II by Bhavsingh Maloth
PDF
Basic JavaScript Tutorial
DOCX
Javascript
PPT
JAVA SCRIPT
PDF
Java script how to
DOC
Basics java scripts
DOC
Introduction to java script
PDF
JS BASICS JAVA SCRIPT SCRIPTING
PPTX
JavaScriptL18 [Autosaved].pptx
PPT
basics of javascript and fundamentals ppt
PPT
Javascript overview and introduction to js
PPT
JS-Slides-1 (1).ppt vbefgvsdfgdfgfggergertgrtgrtgt
PPT
JS-Slides_for_begineers_javascript-1.ppt
PPT
java script programming slide 1 from tn state
PPT
JS-Slides-1hgvhfhgftgfvujguyghvhjbjbnnhg
PPT
Java script
PPT
Java script
Java script by Act Academy
2javascript web programming with JAVA script
WEB PROGRAMMING UNIT II BY BHAVSINGH MALOTH
Web programming UNIT II by Bhavsingh Maloth
Basic JavaScript Tutorial
Javascript
JAVA SCRIPT
Java script how to
Basics java scripts
Introduction to java script
JS BASICS JAVA SCRIPT SCRIPTING
JavaScriptL18 [Autosaved].pptx
basics of javascript and fundamentals ppt
Javascript overview and introduction to js
JS-Slides-1 (1).ppt vbefgvsdfgdfgfggergertgrtgrtgt
JS-Slides_for_begineers_javascript-1.ppt
java script programming slide 1 from tn state
JS-Slides-1hgvhfhgftgfvujguyghvhjbjbnnhg
Java script
Java script

Javascript by geetanjali

  • 1. JAVASCRIPT By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 2. Introduction JavaScript is the most popular scripting language on the internet, and works in all major browsers, such as Internet Explorer, Firefox, Chrome, Opera, and Safari. What You Should Already Know? Before you continue you should have a basic understanding of the following: HTML and CSS By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 3. What is JavaScript? • scripting language • add interactivity to HTML pages •A scripting language is a lightweight programming language •JavaScript is usually embedded directly into HTML pages •JavaScript is an interpreted language (means that scripts execute without preliminary compilation) •Everyone can use JavaScript without purchasing a license By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 4. Java and JavaScript •Java and JavaScript are not same. •Java and JavaScript are two completely different languages in both concept and design. •Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 5. What Can JavaScript do? •JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax. Almost anyone can put small "snippets" of code into their HTML pages •JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element •JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 6. What Can JavaScript do? •JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing •JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser •JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve information on the visitor's computer By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 7. Brief History of JavaScript •JavaScript is an implementation of the ECMAScript language standard. ECMA-262 is the official JavaScript standard. •JavaScript was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared in all browsers since 1996. •The official standardization was adopted by the ECMA organization (an industry standardization association) in 1997. •The ECMA standard (called ECMAScript-262) was approved as an international ISO (ISO/IEC 16262) standard in 1998. •The development is still in progress. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 8. JavaScript: Display Date <html> <head> <title>Javascript</title> </head> <body> <h1>My First Web Page</h1> <script type="text/javascript"> document.write("<p>" + Date() + "</p>"); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 9. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 10. <script> Tag •To insert a JavaScript into an HTML page, use the <script> tag. •Inside the <script> tag use the type attribute to define the scripting language. •The <script> and </script> tells where the JavaScript starts and ends. •Without the <script> tag(s), the browser will treat "document.write" as pure text and just write it to the page. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 11. JavaScript: comments • JavaScript comments can be used to make the code more readable. • Comments can be added to explain the JavaScript • There are Two types of comments in JavaScript: 1) Single line comments 2) Multi-Line comments 1) Single line comments start with //. e.g. <script type="text/javascript"> // Write a heading document.write("<h1>This is a heading</h1>"); // Write two paragraphs: document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 12. JavaScript: comments 2) Multi-Line Comments Multi line comments start with /* and end with */. e.g. <script type="text/javascript"> /* The code below will write one heading and two paragraphs */ document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 13. JavaScript: comments • Use of JavaScript comments 1) To Prevent Execution 2) At the End of a Line 1) To Prevent Execution: The comment is used to prevent the execution of i) single code line: e.g. <script type="text/javascript"> //document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script> ii) code block: e.g. <script type="text/javascript"> /*document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>");*/ </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 14. JavaScript: comments 2) At the End of a Line : e.g. <script type="text/javascript"> document.write("Hello"); // Write "Hello" document.write("World!"); // Write "World!" </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 15. JavaScript: comments • Browsers that do not support JavaScript, will display JavaScript as page content. • To prevent them from doing this, and as a part of the JavaScript standard, the HTML comment tag should be used to "hide" the JavaScript. • Just add an HTML comment tag <!-- before the first JavaScript statement, and a --> (end of comment) after the last JavaScript statement, like this: <html> <body> <script type="text/javascript"> <!-- document.write("<p>" + Date() + "</p>"); //--> </script> </body> /html> The two forward slashes at the end of comment line (//) is the JavaScript comment symbol. This prevents JavaScript from executing the --> tag. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 16. Placing JavaScript 1)Scripts in <head> and <body>: You can place an unlimited number of scripts in your document, and you can have scripts in both the body and the head section at the same time. It is a common practice to put all functions in the head section, or at the bottom of the page. This way they are all in one place and do not interfere with page content. e.g. JavaScript in <body> <html> <body> <h1>My First Web Page</h1> <p id="demo"></p> <script type="text/javascript"> document.getElementById("demo").innerHTML=Date(); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 17. Placing JavaScript e.g. JavaScript in <head> <html> <head> <script type="text/javascript"> function displayDate() { document.getElementById("demo").innerHTML=Date(); } </script> </head> <body> <h1>My First Web Page</h1> <p id="demo"></p> <button type="button" onclick="displayDate()">Display Date</button> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 18. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 19. Placing JavaScript 2) Using an External JavaScript : JavaScript can also be placed in external files. External JavaScript files often contain code to be used on several different web pages. External JavaScript files have the file extension .js. Note: External script cannot contain the <script></script> tags To use an external script, point to the .js file in the "src" attribute of the <script> tag: e.g. <html> <head> <script type="text/javascript" src=“abc.js"></script> </head> <body> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 20. Writing JavaScript • JavaScript is Case Sensitive • JavaScript Statements : JavaScript is a sequence of statements to be executed by the browser. A JavaScript statement is a command to a browser e.g. document.write("Hello World"); • JavaScript Code: <script type="text/javascript"> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 21. Writing JavaScript • JavaScript Blocks: e.g. <script type="text/javascript"> { document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); } </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 22. JavaScript Variables • Variables are "containers" for storing information. • JavaScript variables are used to hold i) values e.g. x=5 ii) expressions e.g. z=x+y. . • A variable can have a short name, like x, or a more descriptive name, like myname. Rules for JavaScript variable names: • Variable names are case sensitive (y and Y are two different variables) • Variable names must begin with a letter or the underscore character By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 23. JavaScript Variables Declaring JavaScript Variables • Creating variables in JavaScript is most often referred to as "declaring" variables. • You declare JavaScript variables with the var keyword: var x; var carname; • After the declaration the variables are empty • assigning values var x=5; var carname="Volvo"; • When you assign a text value to a variable, use quotes around the value. • If you redeclare a JavaScript variable, it will not lose its value. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 24. JavaScript Variables • A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value. e.g. <html> <head> <title>Variables in JavaScript</title> </head> <body> <h1>Variables in JavaScript</h1> <script type="text/javascript"> var firstname; firstname="xyz"; document.write(firstname); document.write("<br>"); firstname="abc"; document.write(firstname); document.write("<br>"); var firstname; document.write(firstname); </script> </body></html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 25. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 26. Scope Of JavaScript Variables Local JavaScript Variables • A variable declared within a JavaScript function becomes LOCAL and can only be accessed within that function. (the variable has local scope). • You can have local variables with the same name in different functions, because local variables are only recognized by the function in which they are declared. • Local variables are destroyed when you exit the function. Global JavaScript Variables • Variables declared outside a function become GLOBAL, and all scripts and functions on the web page can access it. • Global variables are destroyed when you close the page. • If you declare a variable, without using "var", the variable always becomes GLOBAL. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 27. JavaScript Variables Assigning Values to Undeclared JavaScript Variables: If you assign values to variables that have not yet been declared, the variables will automatically be declared as global variables. These statements: x=5; carname="Volvo"; will declare the variables x and carname as global variables (if they don't already exist). JavaScript Arithmetic: As with algebra, you can do arithmetic operations with JavaScript variables: y=x-5; z=y+5; By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 28. Assignments Assignment No. 2: 1. Explain different Text Formatting Tags in HTML with example. 2. Describe local and remote links in HTML with example. 3. What are the different types of lists in HTML. Explain with examples. 4. Explain methods for adding graphics in HTML 5. Explain Table creation in HTML with appropriate examples. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 29. Assignments Assignment No. 3: 1. Describe Image Maps in HTML with example. 2. What are the different ways for defining Style Sheet properties in Cascading Style Sheet. Explain with appropriate examples. 3. What are the different types of SELECTORS that can be used in Cascading Style Sheet. Explain with appropriate examples. 4. Explain different elements in HTML forms that can be added to build interactivity. 5. Describe various HTML editors. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 30. Data Types In JavaScript There are six data types in JavaScript : • Numbers • Strings • Booleans • Null • Undefined • Objects By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 31. Data Types In JavaScript Numbers: Numbers in JavaScript consist of integers, floats, hexadecimals, octal i.e. all numbers are valid in JavaScript. e.g. 4,51.50,-14,0xd <html> <head> <title>Hexadecimal Numbers</title> </head> <body> <h1>My First Web Page</h1> <script type"text/css"> var h=0xe; var i=0x2; var j=h*i; alert(j); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 32. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 33. Data Types In JavaScript Strings: Strings consist of one or more characters surrounded by quotes. e.g. “Hello World”, “B”, “This is ‘another string’” If you need to use the same style of quotes both to enclose the string and within string, then the quotes must be escaped. A single backslash character escapes the quote e.g. • ‘i’m using single quote both outside and within this example. They’re neat.’ • “This is a ”great” example of using ”double quotes” within a string.” By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 34. The table below lists other special characters that can be added to a text string with the backslash sign: Code Outputs ' single quote " double quote backslash n new line r carriage return t tab b backspace f form feed By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 35. Data Types In JavaScript Booleans: Booleans have only two values, true and false. Booleans are bit of a hidden data type in JavaScript i.e. you don’t work with Booleans in the same way that you work with strings and numbers. You simply use an expression that evaluates to a Boolean value. e.g. If (mynumber>18) { //do something } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 36. Data Types In JavaScript Null : Null is special data type in JavaScript. Null is simply nothing. It represents and evaluates to false. Undefined: Undefined is a state, sometimes used like a value, to represent a variable that hasn’t yet contained a value. Objects: JavaScript objects are a collection of properties, each of which contains a primitive value. You can define your own objects using JavaScript, and there are several build-in objects as well. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 37. JavaScript Operators The ECMA-262 standard defines assorted operators of various forms. These include: 1. Additive operators 2. Multiplicative operators 3. Bitwise operators 4. Equality operators 5. Relational operators 6. Unary operators 7. Assignment operators By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 38. JavaScript Operators 1. Additive operators: Operator Description Example Result + Addition x=y+2 x=7 y=5 - Subtraction x=y-2 x=3 y=5 The Addition operator operates in different ways depending on the type of value being added. When a string is used, the addition operator concatenates the left and right arguments. e.g. var str1=“hello”; var str2=“ world”; var result=str1+str2; // result will be the string “hello world” By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 39. JavaScript Operators 2. Multiplicative operators : Operator Description Example Result * Multiplication x=y*2 x=10 y=5 / Division x=y/2 x=2.5 y=5 % Modulus (division x=y%2 x=1 y=5 remainder) By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 40. JavaScript Operators 3. Bitwise operators : Operator Description & AND | OR ^ XOR ~ NOT << Shift Left >> Shift Right By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 41. JavaScript Operators 4. Equality operators : Operator Description == Tests whether two expressions are equal != Tests whether two expressions are not equal === Tests whether two expressions are equal using stricter methods !== Tests whether two expressions are not equal using stricter methods The stricter of two(===) requires not only that the values of a given expression are equal, but the types as well. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 42. JavaScript Operators 5. Relational operators : Operator Description > Greater than < Less than >= Greater than or equal to <= Less than or equal to in Tests whether a value is found in an expression instanceof Tests whether an expression is an instance of an object By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 43. JavaScript Operators 6. Unary operators : Operator Description delete Removes a property void Returns Undefined typeof Returns a string representing the data type ++ Increments a number -- decrements a number + Converts the operand to a number - Negates the operand ~ Bitwise NOT ! Logical NOT By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 44. JavaScript Operators 7. Assignment operators : Operator Example Same As Result = x=y x=5 += x+=y x=x+y x=15 -= x-=y x=x-y x=5 *= x*=y x=x*y x=50 /= x/=y x=x/y x=2 %= x%=y x=x%y x=0 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 45. JavaScript Conditional Statements Conditional statements are used to perform different actions based on different conditions. In JavaScript we have the following conditional statements: • if statement - use this statement to execute some code only if a specified condition is true • if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false • if...else if....else statement - use this statement to select one of many blocks of code to be executed • switch statement - use this statement to select one of many blocks of code to be executed By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 46. JavaScript Conditional Statements if Statement Use the if statement to execute some code only if a specified condition is true. Syntax : if (condition) {   code to be executed if condition is true } e.g. <html> <head> <title>If statement</title> </head> <body> <script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time < 10) { document.write("<b>Good morning</b>"); } </script> <p>This example demonstrates the If statement.</p> <p>If the time on your browser is less than 10, you will get a "Good morning" greeting.</p> </body></html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 47. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 48. JavaScript Conditional Statements If...else Statement : Use the if....else statement to execute some code if a condition is true and another code if the condition is not true. Syntax : if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 49. JavaScript Conditional Statements <html> <head> <title>If else statement</title> </head> <body> <script type="text/javascript"> 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> <p>This example demonstrates the If...Else statement. </p> <p> If the time on your browser is less than 10, you will get a "Good morning" greeting. Otherwise you will get a "Good day" greeting. </p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 50. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 51. JavaScript Conditional Statements If...else if...else Statement : Use the if....else if...else statement to select one of several blocks of code to be executed. Syntax : if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if neither condition1 nor condition2 is true } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 52. JavaScript Conditional Statements <html> <head> <title>If else if statement</title> </head> <body> <script type="text/javascript"> var d = new Date(); var time = d.getHours(); if (time<10) { document.write("<b>Good morning</b>"); } else if (time>=10 && time<16) { document.write("<b>Good day</b>"); } else { document.write("<b>Hello World!</b>"); } </script> <p>This example demonstrates the if..else if...else statement.</p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 53. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 54. JavaScript Conditional Statements The JavaScript Switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax : switch(n) { case 1:   execute code block 1 break; case 2:   execute code block 2 break; default:  code to be executed if n is different from case 1 and 2 } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 55. JavaScript Conditional Statements <html> <head> <title>switch statement</title> </head> <body> <script type="text/javascript"> var d=new Date(); var theDay=d.getDay(); switch (theDay) { case 5: document.write("<b>Finally Friday</b>"); break; case 6: document.write("<b>Super Saturday</b>"); break; case 0: document.write("<b>Sleepy Sunday</b>"); break; default: document.write("<b>I'm really looking forward to this weekend!</b>"); } </script> <p>This JavaScript will generate a different greeting based on what day it is. Note that Sunday=0, Monday=1, Tuesday=2, etc.</p> </body> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 56. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 57. JavaScript Dialog boxes JavaScript has three kind of dialog boxes: 1) Alert box. 2) Confirm box. 3) Prompt box. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 58. JavaScript Dialog boxes 1) Alert box : An alert box is often used if you want to make sure information comes through to the user. When an alert box pops up, the user will have to click "OK" to proceed. Syntax : alert("some text"); Example : <html> <head> <script type="text/javascript"> function show_alert() { alert("Hello! I am an alert box!"); } </script> </head> <body> <input type="button" onclick="show_alert()" value="Show alert box"> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 59. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 60. JavaScript Dialog boxes 2) Confirm box : A confirm box is often used if you want the user to verify or accept something. When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false. Syntax : confirm("sometext"); By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 61. JavaScript Dialog boxes <html> <head> <script type="text/javascript"> function show_confirm() { var r=confirm("Press a button!"); if (r==true) { alert("You pressed OK!"); } else { alert("You pressed Cancel!"); } } </script> </head> <body> <input type="button" onclick="show_confirm()" value="Show a confirm box" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 62. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 63. JavaScript Dialog boxes 2) Prompt box : A prompt box is often used if you want the user to input a value before entering a page. 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. Syntax : prompt("sometext","defaultvalue"); By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 64. JavaScript Dialog boxes <html> <head> <script type="text/javascript"> function show_prompt() { var name=prompt("Please enter your name","abc"); if (name!=null && name!="") { document.write("Hello " + name + "! How are you today?"); } } </script> </head> <body> <input type="button" onclick="show_prompt()" value="Show prompt box" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 65. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 66. JavaScript Functions A JavaScript function is a collection of statements, either named or unnamed, that can be called from elsewhere within a JavaScript program. • To keep the browser from executing a script when the page loads, you can put your script into a function. • A function contains code that will be executed by an event or by a call to the function. • You may call a function from anywhere within a page (or even from other pages if the function is embedded in an external .js file). • Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 67. JavaScript Functions Syntax of Function: function functionName(argument1,argument2,...,argumentX) { //statements go here; } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 68. JavaScript Functions <html> <head> <title>JavaScript Function</title> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()"> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 69. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 70. JavaScript Functions The return Statement : When a function finishes executing its code, a return value can be passed back to the caller. Example: <html> <head> <script type="text/javascript"> function multiplyNums(a,b) { return a*b; } </script> </head> <body> <script type="text/javascript"> document.write(multiplyNums(4,3)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 71. JavaScript Arrays An array is a special variable, which can hold more than one value, at a time. Defining Arrays: 1) regular array : e.g. var empNames=new Array(); // regular array (add an optional integer empNames[0]=“John"; // argument to control array's size) empNames[1]=“Smith"; empNames[2]=“Mark"; 2) condensed array : e.g. var empNames=new Array(“John",“Smith",“Mark"); // condensed array 3) literal array : e.g. var empNames=["John",”Smith",“Mark "]; // literal array By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 72. JavaScript Arrays Access an Array : e.g. document.write(empNames[0]); Modify Values in an Array : e.g. empNames[0]=“Rajesh”; By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 73. Controlling Flow With Loops In JavaScript In JavaScript, there are two different kind of loops: • for - loops through a block of code a specified number of times • while - loops through a block of code while a specified condition is true By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 74. Loops In JavaScript for loops : The for loop is used when you know in advance how many times the script should run. Syntax : for (variable=startvalue;variable<=endvalue;variable=variable+increment) { code to be executed } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 75. for Loop Example <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=5;i++) { document.write("The number is " + i); document.write("<br />"); } </script> <p>Explanation:</p> <p>This for loop starts with i=0.</p> <p>As long as <b>i</b> is less than, or equal to 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 76. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 77. Loops In JavaScript while loops : The while loop loops through a block of code while a specified condition is true. Syntax : while (variable<=endvalue) {   code to be executed } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 78. while Loop Example <html> <body> <script type="text/javascript"> i=0; while (i<=5) { document.write("The number is " + i); document.write("<br />"); i++; } </script> <p>Explanation:</p> <p><b>i</b> is equal to 0.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 79. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 80. Loops In JavaScript Do…while loops : The do...while loop is a variant of the while loop. This loop will execute the block of code ONCE, and then it will repeat the loop as long as the specified condition is true Syntax : do {   code to be executed   } while (variable<=endvalue); By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 81. Do…while Loop Example <html> <body> <script type="text/javascript"> i = 0; do { document.write("The number is " + i); document.write("<br />"); i++; } while (i <= 5) </script> <p>Explanation:</p> <p><b>i</b> equal to 0.</p> <p>The loop will run</p> <p><b>i</b> will increase by 1 each time the loop runs.</p> <p>While <b>i</b> is less than , or equal to, 5, the loop will continue to run.</p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 82. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 83. JavaScript Break and Continue Statements The break Statement The break statement will break the loop and continue executing the code that follows after the loop (if any). Example: <html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 84. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 85. JavaScript Break and Continue Statements The continue statement will break the current loop and continue with the next value. Example: <html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 86. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 87. JavaScript Objects JavaScript is a Object based Language. It allows you to define your own objects. An object is just a special kind of data. An object has properties and methods. • Properties : Properties are the values associated with an object. e.g. <script type="text/javascript"> var txt="Hello World!"; document.write(txt.length); </script> Output:=12 • Methods : Methods are the actions that can be performed on objects. e.g. <script type="text/javascript"> var str="Hello world!"; document.write(str.toUpperCase()); </script> Output:=HELLO WORLD! By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 88. JavaScript Type casting/ Data type Conversion 1) Number Conversions 2) String Conversions 3) Boolean Conversion 1) Number Conversions: The Number() function converts the object argument to a number that represents the object's value. If the value cannot be converted to a legal number, NaN is returned. Syntax: Number(object) ; Parameter Description Optional. A JavaScript object. If no argument is provided, it object returns 0. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 89. JavaScript Type casting 1) Number Conversion: <html> <head> <title>Conversion to Number</title> </head> <body> <script type="text/javascript"> var test1= new Boolean(true); var test2= new Boolean(false); var test3= new Date(); var test4= new String("999"); var test5= new String("999 888"); document.write(Number(test1)+ "<br>"); document.write(Number(test2)+ "<br>"); document.write(Number(test3)+ "<br>"); document.write(Number(test4)+ "<br>"); document.write(Number(test5)+ "<br>"); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 90. Note: If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 91. JavaScript Type casting/ Data type Conversion 2) String Conversions : The String() function converts the value of an object to a string. Syntax: String(object); Parameter Description object Required. A JavaScript object By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 92. JavaScript Type casting <html> <head> <title>Conversion to Number</title> </head> <body> <script type="text/javascript"> var test1= new Boolean(1); var test2= new Boolean(0); var test3= new Boolean(true); var test4= new Boolean(false); var test5= new Date(); var test6= new String("999 888"); var test7=12345; document.write(String(test1)+ "<br />"); document.write(String(test2)+ "<br />"); document.write(String(test3)+ "<br />"); document.write(String(test4)+ "<br />"); document.write(String(test5)+ "<br />"); document.write(String(test6)+ "<br />"); document.write(String(test7)+ "<br />"); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 93. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 94. JavaScript Events Events are actions that can be detected by JavaScript. We define the events in the HTML tags. Examples of events: •A mouse click •A web page or an image loading •Mousing over a hot spot on the web page •Selecting an input field in an HTML form •Submitting an HTML form •A keystroke Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs! By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 95. JavaScript Events Attribute The event occurs when... onblur An element loses focus onchange The content of a field changes onclick Mouse clicks an object ondblclick Mouse double-clicks an object An error occurs when loading a document or an onerror image onfocus An element gets focus onkeydown A keyboard key is pressed onkeypress A keyboard key is pressed or held down onkeyup A keyboard key is released onload A page or image is finished loading By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 96. JavaScript Events Attribute The event occurs when... onmousedown A mouse button is pressed onmousemove The mouse is moved onmouseout The mouse is moved off an element onmouseover The mouse is moved over an element onmouseup A mouse button is released onresize A window or frame is resized onselect Text is selected onunload The user exits the page By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 97. JavaScript Events Example <html> <head> <script type="text/javascript"> function upperCase() { var x=document.getElementById("fname").value document.getElementById("fname").value=x.toUpperCase() } </script> </head> <body> Enter your name: <input type="text" id="fname" onblur="upperCase()"> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 98. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 99. JavaScript Built-in Objects String Object: The String object is used to manipulate a stored piece of text. String objects are created with new String(). Syntax : var txt = new String("string"); or var txt = "string"; String Object Properties : Property Description length Returns the length of a string By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 100. JavaScript Built-in Objects Method Description charAt() Returns the character at the specified index charCodeAt() Returns the Unicode of the character at the specified index Joins two or more strings, and returns a copy of the joined concat() strings fromCharCode() Converts Unicode values to characters Returns the position of the first found occurrence of a indexOf() specified value in a string Returns the position of the last found occurrence of a lastIndexOf() specified value in a string Searches for a match between a regular expression and a match() string, and returns the matches Searches for a match between a substring (or regular replace() expression) and a string, and replaces the matched substring with a new substring By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 101. JavaScript Built-in Objects Method Description Searches for a match between a regular expression and a search() string, and returns the position of the match slice() Extracts a part of a string and returns a new string split() Splits a string into an array of substrings Extracts the characters from a string, beginning at a specified substr() start position, and through the specified number of character Extracts the characters from a string, between two specified substring() indices toLowerCase() Converts a string to lowercase letters toUpperCase() Converts a string to uppercase letters valueOf() Returns the primitive value of a String object By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 102. JavaScript Built-in Objects Examples String Object: <html> <head> <title>String object methods</title> </head> <body> <script type="text/javascript"> var txt="Hello World!"; document.write("World at "+ txt.search("World") + " position <br>"); document.write("sliced string is "+ txt.slice(1,5) + "<br>"); document.write(txt.split(" ")); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 103. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 104. JavaScript Built-in Objects Examples String Object: To search for a specified value within a string <html> <body> <script type="text/javascript"> var str="Hello world!"; document.write(str.match("world") + "<br />"); document.write(str.match("World") + "<br />"); document.write(str.match("worlld") + "<br />"); document.write(str.match("world!")); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 105. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 106. JavaScript Built-in Objects Examples String Object: To convert a string to lowercase or uppercase letters <html> <body> <script type="text/javascript"> var txt="Hello World!"; document.write(txt.toLowerCase() + "<br />"); document.write(txt.toUpperCase()); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 107. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 108. JavaScript Built-in Objects Date Object : The Date object is used to work with dates and times. Date objects are created with new Date(). There are four ways of instantiating a date: var d = new Date(); // current date and time var d = new Date(milliseconds);//milliseconds since 1970/01/01 var d = new Date(dateString); var d = new Date(year, month, day, hours, minutes, seconds, milliseconds); Methods: We can easily manipulate the date by using the methods available for the Date object. Set Dates In the example below we set a Date object to a specific date (14th January 2010): var myDate=new Date(); myDate.setFullYear(2010,0,14); By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 109. JavaScript Built-in Objects In the following example we set a Date object to be 5 days into the future: var myDate=new Date(); myDate.setDate(myDate.getDate()+5); Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself! By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 110. JavaScript Built-in Objects Date Object Methods Method Description getDate() Returns the day of the month (from 1-31) getDay() Returns the day of the week (from 0-6) getFullYear() Returns the year (four digits) getHours() Returns the hour (from 0-23) getMilliseconds() Returns the milliseconds (from 0-999) getMinutes() Returns the minutes (from 0-59) getMonth() Returns the month (from 0-11) getSeconds() Returns the seconds (from 0-59) getTime() Returns the number of milliseconds since midnight Jan 1, 1970 Returns the time difference between GMT and local time, in getTimezoneOffset() minutes Returns the day of the month, according to universal time getUTCDate() (from 1-31) Returns the day of the week, according to universal time (from getUTCDay() 0-6) getUTCFullYear() Returns the year, according to universal time (four digits) By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 111. JavaScript Built-in Objects Method Description getUTCHours() Returns the hour, according to universal time (from 0-23) Returns the milliseconds, according to universal time (from 0- getUTCMilliseconds() 999) getUTCMinutes() Returns the minutes, according to universal time (from 0-59) getUTCMonth() Returns the month, according to universal time (from 0-11) getUTCSeconds() Returns the seconds, according to universal time (from 0-59) Parses a date string and returns the number of milliseconds parse() since midnight of January 1, 1970 setDate() Sets the day of the month (from 1-31) setFullYear() Sets the year (four digits) setHours() Sets the hour (from 0-23) setMilliseconds() Sets the milliseconds (from 0-999) setMinutes() Set the minutes (from 0-59) setMonth() Sets the month (from 0-11) setSeconds() Sets the seconds (from 0-59) By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 112. JavaScript Built-in Objects Method0- Description Sets a date and time by adding or subtracting a specified setTime() number of milliseconds to/from midnight January 1, 1970 Sets the day of the month, according to universal time (from 1- setUTCDate() 31) setUTCFullYear() Sets the year, according to universal time (four digits) setUTCHours() Sets the hour, according to universal time (from 0-23) setUTCMilliseconds() Sets the milliseconds, according to universal time (from 0-999) setUTCMinutes() Set the minutes, according to universal time (from 0-59) setUTCMonth() Sets the month, according to universal time (from 0-11) setUTCSeconds() Set the seconds, according to universal time (from 0-59) setYear() Deprecated. Use the setFullYear() method instead Converts the date portion of a Date object into a readable toDateString() string toGMTString() Deprecated. Use the toUTCString() method instead Returns the date portion of a Date object as a string, using toLocaleDateString() locale conventions Returns the time portion of a Date object as a string, using toLocaleTimeString() locale conventions toLocaleString() Converts a Date object to a string, using locale conventions By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 113. JavaScript Built-in Objects Method Description toString() Converts a Date object to a string toTimeString() Converts the time portion of a Date object to a string toUTCString() Converts a Date object to a string, according to universal time Returns the number of milliseconds in a date string since UTC() midnight of January 1, 1970, according to universal time valueOf() Returns the primitive value of a Date object By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 114. JavaScript Built-in Objects Examples Date Object : Use getFullYear() to get the year. <html> <body> <script type="text/javascript"> var d=new Date(); document.write(d.getFullYear()); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 115. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 116. JavaScript Built-in Objects Examples (Date Object ) <html> <head> <title>Date object</title> </head> <body> <script type="text/javascript"> var mydate= new Date(); var theyear=mydate.getFullYear(); var themonth=mydate.getMonth()+1; var thetoday=mydate.getDate(); document.write("Today's date is: "); document.write(theyear+"/"+themonth+"/"+thetoday+"<br>"); mydate.setFullYear(2100,0,14); var today = new Date(); if (mydate>today) { alert("Today is before 14th January 2100"); } else { alert("Today is after 14th January 2100"); } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 117. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 118. JavaScript Built-in Objects Math Object : The Math object allows you to perform mathematical tasks. Math is not a constructor. All properties/methods of Math can be called by using Math as an object, without creating it. Syntax : var x = Math.PI; // Returns PI var y = Math.sqrt(16); // Returns the square root of 16 By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 119. JavaScript Built-in Objects Math Object Properties: Property Description E Returns Euler's number (approx. 2.718) LN2 Returns the natural logarithm of 2 (approx. 0.693) LN10 Returns the natural logarithm of 10 (approx. 2.302) LOG2E Returns the base-2 logarithm of E (approx. 1.442) LOG10E Returns the base-10 logarithm of E (approx. 0.434) PI Returns PI (approx. 3.14159) SQRT1_2 Returns the square root of 1/2 (approx. 0.707) SQRT2 Returns the square root of 2 (approx. 1.414) By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 120. JavaScript Built-in Objects Method Description abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians Returns the arctangent of x as a numeric value between -PI/2 and PI/2 atan(x) radians atan2(y,x) Returns the arctangent of the quotient of its arguments ceil(x) Returns x, rounded upwards to the nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x,y,z,...,n) Returns the number with the highest value min(x,y,z,...,n) Returns the number with the lowest value pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER Returns the tangent of an angle
  • 121. JavaScript Built-in Objects Examples Math Object : properties <html> <head> <title>Math object properties</title> </head> <body> <script type="text/javascript"> var x=Math.PI; document.write(x); document.write("<br>"); var y = Math.sqrt(16); document.write(y); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 122. JavaScript Built-in Objects Examples Math Object : To use round(). <html> <body> <script type="text/javascript"> document.write(Math.round(0.60) + "<br />"); document.write(Math.round(0.50) + "<br />"); document.write(Math.round(0.49) + "<br />"); document.write(Math.round(-4.40) + "<br />"); document.write(Math.round(-4.60)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 123. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 124. JavaScript Loops JavaScript For...In Statement The for...in statement loops through the properties of an object. Syntax : for (variable in object) { code to be executed } e.g. <html> <body> <script type="text/javascript"> var person={fname:"John",lname:"Doe",age:25}; for (y in person) { document.write(person[y] + " "); } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 125. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 126. JavaScript Error Handling 1) Try...Catch Statement 2) The throw Statement 1) Try...Catch Statement: Syntax: try { //Run some code here } catch(err) { //Handle errors here } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 127. JavaScript Error Handling <html> <head> <script type="text/javascript"> var txt=""; function message() { try { adddlert("Welcome guest!"); } catch(err) { txt="There was an error on this page.nn"; txt+="Error description: " + err.description + "nn"; txt+="Click OK to continue.nn"; alert(txt); } } </script> </head> <body> <input type="button" value="View message" onclick="message()" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 128. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 129. JavaScript Error Handling 2) The throw Statement : The throw statement allows you to create an exception. If you use this statement together with the try...catch statement, you can control program flow and generate accurate error messages. Syntax: throw exception ; By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 130. JavaScript Error Handling <html> <body> <script type="text/javascript"> var x=prompt("Enter a number between 0 and 10:",""); try { if(x>10) { throw "Err1"; } else if(x<0) { throw "Err2"; } else if(isNaN(x)) { throw "Err3"; } } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 131. JavaScript Error Handling catch(er) { if(er=="Err1") { alert("Error! The value is too high"); } if(er=="Err2") { alert("Error! The value is too low"); } if(er=="Err3") { alert("Error! The value is not a number"); } } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 132. The Document Object Model and Browser Hierarchy : By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 133. Document Tree Structure document document. documentElement document.body By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 134. child, sibling, parent By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 135. child, sibling, parent By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 136. child, sibling, parent By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 137. child, sibling, parent By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 138. JavaScript Working with frames frameset.html: <HTML> <HEAD> <TITLE>Frames Values</TITLE> </HEAD> <FRAMESET cols="20%,80%"> <FRAME SRC="jex13.html" name="left_frame"> <FRAME SRC="jex14.html" name="right_frame"> </FRAMESET> </HTML> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 139. JavaScript Working with frames jex14.html: <HTML> <HEAD> <TITLE>JavaScript Example 14</TITLE> </HEAD> <BODY> <FORM name="form1"> <INPUT type="text" name="text1" size="25" value=""> </FORM> </BODY> </HTML> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 140. JavaScript Working with frames jex13.htm: <HTML> <HEAD> <TITLE>JavaScript Example 13</TITLE> </HEAD> <BODY> <FORM> <INPUT type="button" value="What is course name?" onClick="parent.right_frame.document.form1.text1.value=' MCA!'"> </FORM> </BODY> </HTML> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 141. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 142. JavaScript Document Object Document Object Collections : Collection Description anchors[ ] Returns an array of all the anchors in the document forms[ ] Returns an array of all the forms in the document images[ ] Returns an array of all the images in the document links[ ] Returns an array of all the links in the document By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 143. JavaScript Document Object Properties Property Description Returns all name/value pairs of cookies in the cookie document Returns the mode used by the browser to render the documentMode document Returns the domain name of the server that loaded the domain document Returns the date and time the document was last lastModified modified readyState Returns the (loading) status of the document Returns the URL of the document that loaded the referrer current document title Sets or returns the title of the document URL Returns the full URL of the document By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 144. JavaScript Document Object Methods Method Description Closes the output stream previously opened close() with document.open() getElementById() Accesses the first element with the specified id getElementsByName() Accesses all elements with a specified name Accesses all elements with a specified getElementsByTagName() tagname Opens an output stream to collect the output open() from document.write() or document.writeln() Writes HTML expressions or JavaScript code write() to a document Same as write(), but adds a newline character writeln() after each statement By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 145. JavaScript Forms, elements and events •The Form object represents an HTML form. •For each <form> tag in an HTML document, a Form object is created. •Forms are used to collect user input, and contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. •A form can also contain select menus, textarea, fieldset, and label elements. •Forms are used to pass data to a server. •Form Object Collections : Collection Description elements[ ] Returns an array of all elements in a form By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 146. JavaScript Forms, elements and events Form Object Properties : Property Description Sets or returns the value of the accept-charset attribute acceptCharset in a form action Sets or returns the value of the action attribute in a form Sets or returns the value of the enctype attribute in a enctype form length Returns the number of elements in a form Sets or returns the value of the method attribute in a method form name Sets or returns the value of the name attribute in a form target Sets or returns the value of the target attribute in a form By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 147. JavaScript Forms, elements and events Form Object Methods : Method Description reset() Resets a form submit() Submits a form By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 148. JavaScript Forms, elements and events Form Object Events : Event The event occurs when... onreset The reset button is clicked onsubmit The submit button is clicked By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 149. JavaScript Forms, elements and events <html> <body> <form id="frm1"> First name: <input type="text“ name="fname" value="Donald" /><br /> Last name: <input type="text" name="lname" value="Duck" /><br /> <input type="submit" value="Submit" /> </form> <p>Return the value of each element in the form:</p> <script type="text/javascript"> var x=document.getElementById("frm1"); for (var i=0;i<x.length;i++) { document.write(x.elements[i].value); document.write("<br />"); } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 150. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 151. JavaScript Forms Methods reset() <html> <head> <script type="text/javascript"> function formReset() { document.getElementById("frm1").reset(); } </script> </head> <body> <form id="frm1"> First name: <input type="text" name="fname" /><br /> Last name: <input type="text" name="lname" /><br /> <input type="button" onclick="formReset()" value="Reset form" /> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 152. JavaScript Forms Methods submit() <html> <head> <script type="text/javascript"> function formSubmit() { document.getElementById("frm1").submit(); } </script> </head> <body> <p>Enter some text in the fields below, then press the "Submit form" button to submit the form.</p> <form id="frm1" method="get"> First name: <input type="text" name="fname" /><br /> Last name: <input type="text" name="lname" /><br /><br /> <input type="button" onclick="formSubmit()" value="Submit form" /> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 153. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 154. JavaScript Forms Event (onreset) <html> <body> <p>Enter some text in the fields below, then press the Reset button to reset the form.</p> <form onreset="alert('The form will be reset')"> Firstname: <input type="text" name="fname" value="First" /><br /> Lastname: <input type="text" name="lname" value="Last" /> <br /><br /> <input type="reset" value="Reset" /> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 155. JavaScript Forms Event (onsubmit) <html> <head> <script type="text/javascript"> function greeting() { alert("Welcome " + document.forms["frm1"]["fname"].value + "!") } </script> </head> <body> What is your name?<br /> <form name="frm1" action="submit.htm" onsubmit="greeting()"> <input type="text" name="fname" /> <input type="submit" value="Submit" /> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 156. JavaScript Regular Expression Definition: A string that is used to describe or match a set of strings, according to certain syntax. Regular expressions are used to perform powerful pattern-matching and "search-and-replace" functions on text. Syntax : var patt=new RegExp(pattern,modifiers); or more simply: var patt=/pattern/modifiers; •pattern specifies the pattern of an expression •modifiers specify if a search should be global, case-sensitive, etc. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 157. JavaScript Regular Expression Modifiers Modifiers are used to perform case-insensitive and global searches: Modifier Description i Perform case-insensitive matching Perform a global match (find all matches rather than g stopping after the first match) By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 158. JavaScript Regular Expression Modifier i: <html> <body> <script type="text/javascript"> var str = "Visit Siberindia"; var patt1 = /Siberindia/i; document.write(str.match(patt1)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 159. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 160. JavaScript Regular Expression Modifier g: <html> <body> <script type="text/javascript"> var str="Is this all there is?"; var patt1=/is/g; document.write(str.match(patt1)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 161. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 162. JavaScript Regular Expression Modifier g and i: <html> <body> <script type="text/javascript"> var str="Is this all there is?"; var patt1=/is/gi; document.write(str.match(patt1)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 163. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 164. JavaScript Regular Expression Methods Method Description exec() Tests for a match in a string. Returns the first match test() Tests for a match in a string. Returns true or false compile() Compiles a regular expression By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 165. JavaScript Regular Expression Methods test() : The test() method searches a string for a specified value, and returns true or false, depending on the result. Example: <html> <body> <script type="text/javascript"> var patt1=new RegExp("e"); document.write(patt1.test("The best things in life are free")); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 166. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 167. JavaScript Regular Expression Methods exec() : The exec() method searches a string for a specified value, and returns the text of the found value. If no match is found, it returns null. Example: <html> <body> <script type="text/javascript"> var patt1=new RegExp("e"); document.write(patt1.exec("The best things in life are free")); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 168. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 169. JavaScript Regular Expression Methods compile() : The compile() method is used to compile a regular expression during execution of a script. The compile() method can also be used to change and recompile a regular expression. Example: <html> <body> <script> var str="Every man in the world! Every woman on earth!"; var patt=/man/g; var str2=str.replace(patt,"person"); document.write(str2+"<br />"); patt=/(wo)?man/g; patt.compile(patt); str2=str.replace(patt,"person"); document.write(str2); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 170. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 171. JavaScript Regular Expression Brackets : Brackets are used to find a range of characters Expression Description [abc] Find any character between the brackets [^abc] Find any character not between the brackets [0-9] Find any digit from 0 to 9 [A-Z] Find any character from uppercase A to uppercase Z [a-z] Find any character from lowercase a to lowercase z [A-z] Find any character from uppercase A to lowercase z [adgk] Find any character in the given set [^adgk] Find any character outside the given set (red|blue|green) Find any of the alternatives specified By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 172. JavaScript Regular Expression <html> <body> <script type="text/javascript"> var str="Is this all there is?"; var patt1=/[a-h]/g; document.write(str.match(patt1)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 173. JavaScript Regular Expression By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 174. JavaScript Regular Expression Metacharacters :Metacharacters are characters with a special meaning: Metacharacter Description . Find a single character, except newline or line terminator w Find a word character W Find a non-word character d Find a digit D Find a non-digit character s Find a whitespace character S Find a non-whitespace character b Find a match at the beginning/end of a word B Find a match not at the beginning/end of a word 0 Find a NUL character By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 175. JavaScript Regular Expression Metacharacters :Metacharacters are characters with a special meaning: Metacharacter Description n Find a new line character f Find a form feed character r Find a carriage return character t Find a tab character v Find a vertical tab character Find the character specified by an octal xxx number xxx Find the character specified by a hexadecimal xdd number dd Find the Unicode character specified by a uxxxx hexadecimal number xxxx By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 176. JavaScript Regular Expression <html> <body> <script type="text/javascript"> var str="This is my car!"; var patt1=/c.r/g; document.write(str.match(patt1)); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 177. JavaScript Regular Expression Properties Property Description global Specifies if the "g" modifier is set ignoreCase Specifies if the "i" modifier is set lastIndex The index at which to start the next match source The text of the RegExp pattern By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 178. JavaScript Regular Expression Properties <html> <body> <script type="text/javascript"> var str="The rain in Spain stays mainly in the plain"; var patt1=/ain/g; while (patt1.test(str)==true) { document.write("'ain' found. Index now at: "+patt1.lastIndex); document.write("<br />"); } </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 179. JavaScript Regular Expression Properties By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 180. JavaScript Form Validation JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be: •has the user left required fields empty? •has the user entered a valid e-mail address? •has the user entered a valid date? •has the user entered text in a numeric field? By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 181. JavaScript Form Validation (Required Fields) <html> <head> <script type="text/javascript"> function validateForm() { var x=document.forms["myForm"]["fname"].value if (x==null || x=="") { alert("First name must be filled out"); return false; } } </script> </head> <body> <form name="myForm" action="http://localhost/myweb/test1.asp" onsubmit="return validateForm()" method="post"> First name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 182. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 183. JavaScript Cookies cookie: a small amount of information sent by a server to a browser, and then sent back by the browser on future page requests. cookies have many uses: •authentication •user tracking •maintaining user preferences, shopping carts, etc. A cookie's data consists of a single name/value pair, sent in the header of the client's HTTP GET or POST request By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 184. JavaScript Cookies How cookies are sent 1) when the browser requests a page, the server may send back a cookie(s) with it 2) if your server has previously sent any cookies to the browser, the browser will send them back on subsequent requests alternate model: client-side JavaScript code can set/get By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 185. JavaScript Cookies Myths: •Cookies are like worms/viruses and can erase data from the user's hard disk. •Cookies are a form of spyware and can steal your personal information. •Cookies generate popups and spam. •Cookies are only used for advertising. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 186. JavaScript Cookies Facts: •Cookies are only data, not program code. •Cookies cannot erase or read information from the user's computer. •Cookies are usually anonymous (do not contain personal information). •Cookies CAN be used to track your viewing habits on a particular site. A. Bhosale. Assistant Professor, SIBER By Mrs. Geetanjali
  • 187. JavaScript Cookies How long does a cookie exist? session cookie : the default type; a temporary cookie that is stored only in the browser's memory when the browser is closed, temporary cookies will be erased can not be used for tracking long-term information safer, because no programs other than the browser can access them persistent cookie : one that is stored in a file on the browser's computer can track long-term information potentially less secure, because users (or programs they run) can By Mrs.cookie files,Bhosale. Assistant Professor, SIBER open Geetanjali A. see/change the cookie
  • 188. JavaScript Cookies Examples of cookies: 1) Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie 2) Password cookie - The first time a visitor arrives to your web page, he or she must fill in a password. The password is then stored in a cookie. Next time the visitor arrives at your page, the password is retrieved from the cookie 3) Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 189. JavaScript Cookies Stateless • When stateless protocol is used between a server and the client, the server does not remember anything. • It treats any message from a client as the client's first message and responds with the same effects every time. • Stateless means there is no record of previous interactions and each interaction request has to be handled based entirely on information that comes with it. • Example : http Stateful • Stateful protocol means the server remembers what a client has done before. • The computer or program keeps track of the state of interaction, usually by setting values in a storage field designated for that purpose. • Example: FTP, Telnet By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 190. JavaScript Form Validation (Numeric value) <html> <head> <title>Numeric TextBox</title> <script lanugage="javascript"> function test() { var value=document.form1.t.value; var ch,i; for(i=0;i<value.length;i++) { ch=value.charAt(i); if (ch >= "0" && ch <="9") continue; else { alert("Non-numeric character is not allowed..."); break; } } } </script> </head> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 191. JavaScript Form Validation (Numeric value) <body> <form name="form1"> <input type="text" name="t" onChange="test();"> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 192. JavaScript Form Validation (accept 4 digit code) <html> <head> <title>Regex in JavaScript</title> <script language="JavaScript“> function validate(code) { var fourDigitCode = /^([a-zA-Z0-9]{4})$/; var status = document.getElementById("status"); if(fourDigitCode.test(code) == false) { status.innerHTML = "Enter a four digit code.“; } else { status.innerHTML = "Success!"; } } </script> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 193. JavaScript Form Validation (accept 4 digit code) <style type="text/css"> <!-- div { width: 100%; text-align: center; margin-top:150px; } span { color: #000099; font: 8pt verdana; font-weight:bold; text-decoration:none; } input { color: #000000; background: #F8F8F8; border: 1px solid #353535; width:250px; font: 8pt verdana; font-weight:normal; text-decoration:none; margin-top:5px; } --> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER </style>
  • 194. JavaScript Form Validation (accept 4 digit code) </head> <body> <div> <span id="status">Enter a four digit code.</span><br> <input type="text" name="code" onkeyup="validate(this.value);"> </div> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 195. JavaScript Form Validation (number Validation) <html> <head> <title>Numeric TextBox</title> <script type='text/javascript'> function isNumeric(elem, helperMsg) { var numericExpression = /^[0-9]+$/; if(elem.value.match(numericExpression)) { return true; } else { alert(helperMsg); elem.focus(); return false; } } </script> </head> <body> <form> Numbers Only: <input type='text' id='numbers'/> <input type='button' onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')" By Mrs. Geetanjali A. Bhosale. Assistant Professor, value='Check Field' /> SIBER </form> </body></html>
  • 196. JavaScript Objects Creating Your Own Objects : 1. Create a direct instance of an object personObj=new Object(); personObj.firstname="John"; personObj.lastname="Doe"; personObj.age=50; personObj.eyecolor="blue"; OR personObj={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}; You can call a method with the following syntax: objName.methodName() e.g. personObj.sleep(); By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 197. JavaScript Objects Creating Your Own Objects : 2. Create an object constructor function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; } Once you have the object constructor, you can create new instances of the object, like this: var myFather=new person("John","Doe",50,"blue"); var myMother=new person("Sally","Rally",48,"green"); By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 198. JavaScript Objects You can also add some methods to the person object. This is also done inside the function: function person(firstname,lastname,age,eyecolor) { this.firstname=firstname; this.lastname=lastname; this.age=age; this.eyecolor=eyecolor; this.newlastname=newlastname; } Note that methods are just functions attached to objects. Then we will have to write the newlastname() function: function newlastname(new_lastname) { this.lastname=new_lastname; } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 199. JavaScript Strengths and weaknesses Strengths of JavaScript JavaScript offers several strengths to the programmer including a short development cycle, ease-of-learning, and small size scripts. These strengths mean that JavaScript can be easily and quickly used to extend HTML pages already on the Web. 1) Quick Development Because JavaScript does not require time-consuming compilation, scripts can be developed in a relatively short period of time. This is enhanced by the fact that most of the interface features, such as dialog boxes, forms, and other GUI elements, are handled by the browser and HTML code. JavaScript programmers don't have to worry about creating or handling these elements of their applications. 2) Easy to Learn While JavaScript may share many similarities with Java, it doesn't include the complex syntax and rules of Java. By learning just a few commands and simple rules of syntax, along with understanding the way objects are used in JavaScript, it is possible to begin creating fairly sophisticated programs. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 200. JavaScript Strengths and weaknesses . 3) Platform Independence Because the World Wide Web, by its very nature, is platform-independent, JavaScript programs created for Netscape Navigator are not tied to any specific hardware platform or operating system. The same program code can be used on any platform for which Navigator 2.0 is available. 4) Small Overhead JavaScript programs tend to be fairly compact and are quite small, compared to the binary applets produced by Java. This minimizes storage requirements on the server and download times for the user. In addition, because JavaScript programs usually are included in the same file as the HTML code for a page, they require fewer separate network accesses. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 201. JavaScript Strengths and weaknesses Weaknesses of JavaScript As would be expected, JavaScript also has its own unique weaknesses. These include a limited set of built-in methods, the inability to protect source code from prying eyes, and the fact that JavaScript still doesn't have a mature development and debugging environment. 1. Limited Range of Built-In Methods Early versions of the Navigator 2.0 beta included a version of JavaScript that was rather limited. In the final release of Navigator 2, the number of built-in methods had significantly increased, but still didn't include a complete set of methods to work with documents and the client windows. With the release of Navigator 3, things have taken a further step forward with the addition of numerous methods, properties, and event handlers. 2. No Code Hiding :Because the source code of JavaScript script presently must be included as part of the HTML source code for a document, there is no way to protect code from being copied and reused by people who view your Web pages. This raises concerns in the software industry about protection of intellectual property. The consensus is that JavaScript scripts are basically freeware at this point in By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER time.
  • 202. JavaScript Strengths and weaknesses 3. Lack of Debugging and Development Tools Most well-developed programming environments include a suite of tools that make development easier and simplify and speed up the debugging process. Currently, there are some HTML editors and programming editors that provide JavaScript support. In addition, there are some on-line tools for debugging and testing JavaScript scripts. However, there are really no integrated development environments such as those available for Java, C, or C++. LiveWire from Netscape provides some development features but is not a complete development environment for client-side JavaScript. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 203. JavaScript Browser Objects • Window • Navigator • Screen • History • Location By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 204. JavaScript Browser Objects • Window: The window object represents an open window in a browser. If a document contain frames (<frame> or <iframe> tags), the browser creates one window object for the HTML document, and one additional window object for each frame. Window Object Properties: Property Description Returns a Boolean value indicating whether a window has been closed or closed not defaultStatus Sets or returns the default text in the statusbar of a window document Returns the Document object for the window Returns an array of all the frames (including iframes) in the current frames window history Returns the History object for the window innerHeight Sets or returns the inner height of a window's content area By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 205. Property Description innerWidth Sets or returns the inner width of a window's content area length Returns the number of frames (including iframes) in a window location Returns the Location object for the window name Sets or returns the name of a window navigator Returns the Navigator object for the window opener Returns a reference to the window that created the window outerHeight Sets or returns the outer height of a window, including toolbars/scrollbars outerWidth Sets or returns the outer width of a window, including toolbars/scrollbars Returns the pixels the current document has been scrolled (horizontally) pageXOffset from the upper left corner of the window Returns the pixels the current document has been scrolled (vertically) pageYOffset from the upper left corner of the window parent Returns the parent window of the current window screen Returns the Screen object for the window screenLeft Returns the x coordinate of the window relative to the screen screenTop Returns the y coordinate of the window relative to the screen screenX Returns the x coordinate of the window relative to the screen screenY Returns the y coordinate of the window relative to the screen self Returns the current window status Sets the text in the statusbar of a window top By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER Returns the topmost browser window
  • 206. JavaScript Browser Objects (Window) <html> <head> <script type="text/javascript"> var myWindow; function openWin() { myWindow=window.open("","","width=400,height=200"); } function closeWin() { if (myWindow) { myWindow.close(); } } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 207. JavaScript Browser Objects (Window) function checkWin() { if (!myWindow) { document.getElementById("msg").innerHTML="'myWindow' has never been opened!"; } else { if (myWindow.closed) { document.getElementById("msg").innerHTML="'myWindow' has been closed!"; } else { document.getElementById("msg").innerHTML="'myWindow' has not been closed!"; } } } By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 208. JavaScript Browser Objects (Window) </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> <input type="button" value="Close 'myWindow'" onclick="closeWin()" /> <br /><br /> <input type="button" value="Has 'myWindow' been closed?" onclick="checkWin()" /> <br /><br /> <div id="msg"></div> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 209. JavaScript Browser Objects (Window) <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('',''); myWindow.innerHeight=“200"; myWindow.innerWidth=“200"; myWindow.document.write("<p>This is 'myWindow'</p>"); myWindow.focus(); } </script> </head> <body> <input type="button" value="Open 'myWindow'" onclick="openWin()" /> </body> </html> Note:The innerHeight and innerWidth properties only works in Firefox. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 210. JavaScript Browser Objects (Window) Window Object Methods: Method Description alert() Displays an alert box with a message and an OK button blur() Removes focus from the current window clearInterval() Clears a timer set with setInterval() clearTimeout() Clears a timer set with setTimeout() close() Closes the current window confirm() Displays a dialog box with a message and an OK and a Cancel button createPopup() Creates a pop-up window focus() Sets focus to the current window moveBy() Moves a window relative to its current position moveTo() Moves a window to the specified position open() Opens a new browser window print() Prints the content of the current window By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 211. JavaScript Browser Objects (Window) Window Object Methods: Method Description prompt() Displays a dialog box that prompts the visitor for input resizeBy() Resizes the window by the specified pixels resizeTo() Resizes the window to the specified width and height scrollBy() Scrolls the content by the specified number of pixels scrollTo() Scrolls the content to the specified coordinates Calls a function or evaluates an expression at specified intervals (in setInterval() milliseconds) Calls a function or evaluates an expression after a specified number of setTimeout() milliseconds By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 212. JavaScript Browser Objects (Window) popupwin.html (program for createPopup() method) <html> <head> <script type="text/javascript"> function show_popup() { var p=window.createPopup(); var pbody=p.document.body; pbody.style.backgroundColor="lime"; pbody.style.border="solid black 1px"; pbody.innerHTML="This is a pop-up! Click outside the pop-up to close."; p.show(150,150,200,50,document.body); } </script> </head> <body> <button onclick="show_popup()">Show pop-up!</button> <p><b>Note:</b> The createPopup() method only works in IE!</p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 213. JavaScript Browser Objects (Window) winblur.html (program for blur() method) <html> <head> <script type="text/javascript"> function openWin() { myWindow=window.open('','','width=200,height=100'); myWindow.document.write("<p>This is 'myWindow'</p>"); myWindow.blur(); } </script> </head> <body> <input type="button" value="Open window" onclick="openWin()" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 214. JavaScript Browser Objects (Window) Window open() Method : Syntax: window.open(URL,name,specs,replace) Parameter Description Optional. Specifies the URL of the page to open. If no URL is specified, a new URL window with about:blank is opened Optional. Specifies the target attribute or the name of the window. The following values are supported: •_blank - URL is loaded into a new window. This is default name •_parent - URL is loaded into the parent frame •_self - URL replaces the current page •_top - URL replaces any framesets that may be loaded •name - The name of the window specs Optional. A comma-separated list of items. Optional.Specifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported: replace •true - URL replaces the current document in the history list •false - URL creates a new entry in the history list By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 215. JavaScript Browser Objects (Window) specs Whether or not to display the window in theater mode. Default is no. IE channelmode=yes|no|1|0 only directories=yes|no|1|0 Whether or not to add directory buttons. Default is yes. IE only Whether or not to display the browser in full-screen mode. Default is no. fullscreen=yes|no|1|0 A window in full-screen mode must also be in theater mode. IE only height=pixels The height of the window. Min. value is 100 left=pixels The left position of the window location=yes|no|1|0 Whether or not to display the address field. Default is yes menubar=yes|no|1|0 Whether or not to display the menu bar. Default is yes resizable=yes|no|1|0 Whether or not the window is resizable. Default is yes scrollbars=yes|no|1|0 Whether or not to display scroll bars. Default is yes status=yes|no|1|0 Whether or not to add a status bar. Default is yes Whether or not to display the title bar. Ignored unless the calling titlebar=yes|no|1|0 application is an HTML Application or a trusted dialog box. Default is yes toolbar=yes|no|1|0 Whether or not to display the browser toolbar. Default is yes top=pixels The top position of the window. IE only width=pixels By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 216. JavaScript Browser Objects (Window) customalert.html <html> <head> <title>Custom Alert</title> <script language="javascript"> function makeAlert(height,width,message) { var win=window.open("","","height="+height+",width="+width); win.document.open(); var text=""; text+="<html><head><title>Alert</title></head><body bgcolor='#ffffff'>"; text+=message + "<form><center>"; text+="<input type=button value=' OK ' onClick='self.close();' "; text+="<</center></form></body></html>"; win.document.write(text); win.document.close(); } </script> </head> <body> <form> <input type="button" value="Make an Alert" onClick="makeAlert(85,200,'<center>This is a custom Alert! </center>')"> </form> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 217. JavaScript Browser Objects (History) History Object: The history object contains the URLs visited by the user (within a browser window). The history object is part of the window object and is accessed through the window.history property. History Object Properties : Property Description length Returns the number of URLs in the history list Syntax: history.length Note: Internet Explorer and Opera start at 0, while Firefox, Chrome, and Safari start at 1. By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 218. JavaScript Browser Objects (History) <html> <body> <script type="text/javascript"> document.write("Number of URLs in history list: " + history.length); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 219. JavaScript Browser Objects (History) History Object Methods : Method Description back() Loads the previous URL in the history list forward() Loads the next URL in the history list go() Loads a specific URL from the history list By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 220. JavaScript Browser Objects (History) historyBack.html <html> <head> <script type="text/javascript"> function goBack() { window.history.back() } </script> </head> <body> <input type="button" value="Back" onclick="goBack()" /> <p>Notice that clicking on the Back button here will not result in any action, because there is no previous URL in the history list.</p> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 221. JavaScript Browser Objects (Location) Location Object : The location object contains information about the current URL. The location object is part of the window object and is accessed through the window.location property. Location Object Properties : Property Description hash Returns the anchor portion of a URL host Returns the hostname and port of a URL hostname Returns the hostname of a URL href Returns the entire URL pathname Returns the path name of a URL port Returns the port number the server uses for a URL protocol Returns the protocol of a URL search Returns the query portion of a URL By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 222. JavaScript Browser Objects (Location) <html> <head> <title>Location Object</title> </head> <body> <script type="text/javascript"> document.write(location.hash); document.write(location.host); document.write(location.hostname); document.write(location.href); document.write(location.pathname); document.write(location.port); document.write(location.protocol); document.write(location.search); </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 223. JavaScript Browser Objects (Location) Location Object Methods : Method Description assign() Loads a new document reload() Reloads the current document replace() Replaces the current document with a new one By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 224. JavaScript Browser Objects (Location) <html> <head> <script type="text/javascript"> function newDoc() { window.location.assign("http://www.google.com") } </script> </head> <body> <input type="button" value="Load new document" onclick="newDoc()" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 225. JavaScript Browser Objects (Location) <html> <head> <script type="text/javascript"> function reloadPage() { window.location.reload() } </script> </head> <body> <input type="button" value="Reload page“ onclick="reloadPage()" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 226. JavaScript Browser Objects (Location) <html> <head> <script type="text/javascript"> function replaceDoc() { window.location.replace("http://www.google.com") } </script> </head> <body> <input type="button" value="Replace document" onclick="replaceDoc()" /> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 227. JavaScript Browser Detection The Navigator Object: The Navigator object contains all information about the visitor's browser: Navigator Object Properties : Property Description appCodeName Returns the code name of the browser appName Returns the name of the browser appVersion Returns the version information of the browser Determines whether cookies are enabled in the cookieEnabled browser platform Returns for which platform the browser is compiled Returns the user-agent header sent by the browser userAgent to the server By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 228. JavaScript Browser Detection Navigator Object Methods Method Description Specifies whether or not the browser has Java javaEnabled() enabled Specifies whether or not the browser has data taintEnabled() tainting enabled By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 229. JavaScript Browser Detection <html> <body> <div id="example"></div> <script type="text/javascript"> txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; txt+= "<p>Browser Name: " + navigator.appName + "</p>"; txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; txt+= "<p>Platform: " + navigator.platform + "</p>"; txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; document.getElementById("example").innerHTML=txt; </script> </body> </html> By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 230. JavaScript Browser Detection By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER
  • 231. JavaScript Browser Objects (Screen) The screen object contains information about the visitor's screen. Screen Object Properties: Property Description availHeight Returns the height of the screen (excluding the Windows Taskbar) availWidth Returns the width of the screen (excluding the Windows Taskbar) colorDepth Returns the bit depth of the color palette for displaying images height Returns the total height of the screen pixelDepth Returns the color resolution (in bits per pixel) of the screen width Returns the total width of the screen By Mrs. Geetanjali A. Bhosale. Assistant Professor, SIBER