JavaScript
JAVASCRIPT
• JavaScript is used in millions of Web pages to improve
  the design, validate forms, detect browsers, create
  cookies, and much more.
• JavaScript is the most popular scripting language on the
  internet, and works in all major browsers, such as
  Internet Explorer, Mozilla, Firefox, Netscape, Opera.
            WHAT IS JAVASCRIPT?
• JavaScript was designed to add interactivity to HTML pages
• JavaScript is a scripting language (a scripting language is a
  lightweight programming language)
• A JavaScript consists of lines of executable computer code
• A 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
Why Study JavaScript?
• JavaScript is one of the 3 languages all web
  developers must learn:
     • HTML to define the content of web pages
     • CSS to specify the layout of web pages
     • JavaScript to program the behavior of web pages
  Are Java and JavaScript the Same?
• NO!
• 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++.
              JavaScript vs. PHP
• similarities:
  –   both are interpreted, not compiled
  –   both are relaxed about syntax, rules, and types
  –   both are case-sensitive
  –   both have built-in regular expressions for
      powerful text processing
                           CS380                        6
            JavaScript vs. PHP
• differences:
  – JS is more object-oriented
  – JS focuses on user interfaces and interacting with
    a document; PHP is geared toward HTML output
    and file/form processing
  – JS code runs on the client's browser; PHP code
    runs on the web server
             JS <3
                         CS380                           7
        JavaScript Capabilities
• Improve the user interface of a website
• Make your site easier to navigate
• Easily create pop-up alert, windows
• Replace images on a page without reload the
  page
• Form validation
• Many others …
   How to Put a JavaScript Into an HTML
                  Page?
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
           Embedding JavaScript
<html>
<head>
<title>First JavaScript Program</title>
</head>
<body>
<script language=“JavaScript”
   src=“your_source_file.js”></script>
</body>
</html>
  Hide JavaScript from incompatible browsers
<script language=“JavaScript”>
<!– begin hiding JavaScript
// single-line comment, /* … */ multiple-line
   comment
End hiding JavaScript -->
</script>
<noscript>
Your browser does not support JavaScript.
</noscript>
Ending Statements With a Semicolon?
• With traditional programming languages, like
  C++ and Java, each code statement has to end
  with a semicolon (;).
• Many programmers continue this habit when
  writing JavaScript, but in general, semicolons
  are optional! However, semicolons are
  required if you want to put more than one
  statement on a single line.
             JavaScript Variables
• Variables are used to store data.
• A variable is a "container" for information you want
  to store. A variable's value can change during the
  script. You can refer to a variable by name to see its
  value or to change its value.
• Rules for variable names:
  – Variable names are case sensitive
  – They must begin with a letter or the underscore character
      • strname – STRNAME (not same)
                              Variables
• JavaScript allows you to declare and use variables to
  store values.
• How to assign a name to a variable?
      –   Include uppercase and lowercase letters
      –   Digits from 0 through 9
      –   The underscore _ and the dollar sign $
      –   No space and punctuation characters
      –   Case-sensitive
      –   No reserved words or keywords
INE2720 – Web Application   All copyrights reserved by C.C. Cheung
                                                                     14
Software Development                         2003.
       Which one is legal?
My_variable
                       Legal
$my_variable
1my_example
_my_variable
@my_variable
My_variable_example
++my_variable
%my_variable
                       Illegal
#my_variable
~my_variable
myVariableExample
                                 15
    HTML Forms and JavaScript
• JavaScript is very good at processing user
  input in the web browser
• HTML <form> elements receive input
• Forms and form elements have unique names
  – Each unique element can be identified
  – Uses JavaScript Document Object Model (DOM)
Naming Form Elements in HTML
<form name="addressform">
Name: <input name="yourname"><br />
Phone: <input name="phone"><br />
Email: <input name="email"><br />
</form>
         Forms and JavaScript
document.formname.elementname.value
Thus:
document.addressform.yourname.value
document.addressform.phone.value
document.addressform.email.value
                   Using Form Data
Personalising an alert box
<form name="alertform">
Enter your name:
<input type="text" name="yourname">
<input type="button" value= "Go"
  onClick="window.alert('Hello ' + →
  document.alertform.yourname.value);">
</form>
                  JavaScript Operators
Arithmetic Operators                      Operator
                                             +
                                                     Description
                                                     Addition
                                                                         Example
                                                                         x=2
                                                                                   Result
                                                                                     4
(İşleçler, iki ya da daha fazla değer                                    y=2
    üzerinde işlem yapılmasını sağlar.                                   x+y
                                              -      Subtraction         x=5         3
    JavaScript içinde aritmetik ve
                                                                         y=2
    hesaplama işleçleri olmak üzere iki                                  x-y
    tür işleç kullanılır)                    *       Multiplication      x=5         20
                                                                         y=4
                                                                         x*y
                                              /      Division            15/5        3
                                                                         5/2        2,5
                                             %       Modulus (division   5%2         1
                                                         remainder)
                                                                         10%8        2
                                                                         10%2        0
                                             ++      Increment           x=5        x=6
                                                                         x++
                                             --      Decrement           x=5        x=4
                                                                         x--
              JavaScript Operators – 2
Assignment Operators                   Operator   Example   Is The Same As
(Atama deyimi (=), bir değişkene bir
   değerin atanmasını sağlar.          =          x=y       x=y
   Değişkenlere türlerine ve
   tanımlamalarına uygun olan          +=         x+=y      x=x+y
   herhangi bir değer atanabilir.)
                                       -=         x-=y      x=x-y
                                       *=         x*=y      x=x*y
                                       /=         x/=y      x=x/y
                                       %=         x%=y      x=x%y
               JavaScript Operators - 3
Comparison Operators                        Operator
                                            ==
                                                       Description
                                                       is equal to
                                                                                  Example
                                                                                  5==8 returns false
(Karşılaştırma işleci, iki ya da daha çok
                                            ===        is equal to (checks for    x=5
   değeri birbiriyle karşılaştırarak True                    both value and
                                                             type)                y="5"
   ya da False olarak mantıksal bir
   değer döndürür.)                                                               x==y returns true
                                                                                  x===y returns
                                                                                      false
                                            !=         is not equal               5!=8 returns true
                                            >          is greater than            5>8 returns false
                                            <          is less than               5<8 returns true
                                            >=         is greater than or equal   5>=8 returns false
                                                             to
                                            <=         is less than or equal to   5<=8 returns true
               JavaScript Operators - 4
                                            Operator   Description   Example
Logical Operators                           &&         and           x=6
(İkili işleçler birden çok karşılaştırma                             y=3
    işlemini tek bir koşul ifadesi olarak
    birleştirirler.)                                                 (x < 10 && y > 1)
                                                                          returns true
                                            ||         or            x=6
                                                                     y=3
                                                                     (x==5 || y==5)
                                                                         returns false
                                            !          not           x=6
                                                                     y=3
                                                                     !(x==y) returns
                                                                          true
 JavaScript Can Change HTML Content
• One of many JavaScript HTML methods is getElementById().
• This example uses the method to "find" an HTML element (with
  id="demo") and changes the element content (innerHTML) to
  "Hello JavaScript":
JavaScript Can Change HTML Attributes
• This example changes an HTML image by changing the src (source) attribute
  of an <img> tag:
JavaScript Can Change HTML Styles (CSS)
• Changing the style of an HTML element, is a variant of changing an HTML
  attribute:
JavaScript Can Hide HTML Elements
• Hiding HTML elements can be done by changing the display style:
    JavaScript Functions and Events
• A JavaScript function is a block of JavaScript code, that can be
  executed when "asked" for.
• For example, a function can be executed when an event occurs,
  like when the user clicks a button.
                  External JavaScript
• Scripts can also be placed in external files:
• External scripts are practical when the same code is used in many different
  web pages.
• JavaScript files have the file extension .js.
• To use an external script, put the name of the script file in the src (source)
  attribute of a <script> tag:
      External JavaScript Advantages
• Placing JavaScripts in external files has some
  advantages:
     • It separates HTML and code
     • It makes HTML and JavaScript easier to read and maintain
     • Cached JavaScript files can speed up page loads
                  JavaScript Output
• JavaScript does NOT have any built-in print or display
  functions.
• JavaScript Display Possibilities
  – JavaScript can "display" data in different ways:
      •   Writing into an alert box, using window.alert().
      •   Writing into the HTML output using document.write().
      •   Writing into an HTML element, using innerHTML.
      •   Writing into the browser console, using console.log().
     JavaScript: Object-Based Language
• There are three object categories in JavaScript: Native
  Objects, Host Objects, and User-Defined Objects.
   – Native objects: defined by JavaScript.
       • String, Number, Array, Image, Date, Math, etc.
   – Host objects : supplied and always available to JavaScript by the
     browser environment.
       • window, document, forms, etc.
   – User-defined objects : defined by the author/programmer
• Initially, we will use host objects created by the browser
  and their methods and properties
                 JavaScript Objects
• You define (and create) a JavaScript object with an object literal:
         What can JavaScript Do?
• Event handlers can be used to handle, and verify, user
  input, user actions, and browser actions:
  –   Things that should be done every time a page loads
  –   Things that should be done when the page is closed
  –   Action that should be performed when a user clicks a button
  –   Content that should be verified when a user inputs data
• Many different methods can be used to let JavaScript
  work with events:
  – HTML event attributes can execute JavaScript code directly
  – HTML event attributes can call JavaScript functions
  – You can assign your own event handler functions to HTML
    elements
  – You can prevent events from being sent or being handled
                  JavaScript Data Types
• In JavaScript there are 5 different data types that can contain values:
   –   string
   –   number
   –   boolean
   –   object
   –   function
• There are 3 types of objects:
   – Object
   – Date
   – Array
• And 2 data types that cannot contain values:
   – null
   – undefined
        JavaScript Popup Boxes
• 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.
<script>
alert(“Image is too large!")
</script>
      JavaScript Popup 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.
     JavaScript Popup Boxes - 2
• var r = confirm("Press a button");
  if (r == true) {
     x = "You pressed OK!";
  } else {
     x = "You pressed Cancel!";
  }
      JavaScript Popup Boxes - 3
• 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.
             Prompt Box Example
Syntax:
window.prompt("sometext","defaultText");
Example:
var person = prompt ("Please enter your name", "Harry Potter");
   if (person != null) {
      document.getElementById("demo").innerHTML = "Hello " +
   person + "! How are you today?";
   }
                            Three methods
              <script language="JavaScript">
              alert("This is an Alert method");
              confirm("Are you OK?");
              prompt("What is your name?");
              prompt("How old are you?","20");
              </script>
INE2720 – Web Application      All copyrights reserved by C.C. Cheung
                                                                        41
Software Development                            2003.
            JS Examples -1
<script>
x=3
y=20*x+12
alert(y)
</script>
               Examples -2
<script>
s1=12
s2=28
sum=s1+s2
document.write(“the sum is: "+sum)
</script>
             Conditional Statements
• Very often when you write code, you want to perform different actions for
  different decisions. You can use conditional statements in your code to do
  this.
In JavaScript we have the following conditional statements:
 • if statement - use this statement if you want to execute some code only if
    a specified condition is true
 • if...else statement - use this statement if you want 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 if you want to select one
    of many blocks of code to be executed
 • switch statement - use this statement if you want to select one of many
    blocks of code to be executed
           Conditional Statements - 2
if (condition)
{
code to be executed if condition is true
}
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
                     Dynamic Pages
• A script can adapt the content based on explicit input from
  the user or other information
   – System clock: Time of day
   – Hidden input
   – Cookies
• User input can be collected by invoking the prompt method of
  a window object
   – This will display a dialog box that prompts user for input
welcome5.html
      JavaScript is a loosely typed language. Variables take on any
    (1 of 2)
      data type depending on the value assigned.
                             Value returned by the prompt
                           method of the window object is
                           assigned to the variable name
              “+” symbol can be
              used for text
              concatenation as well
              as arithmetic operator
                                                                                  When the user clicks OK, the value
                                                                                  typed by the user is returned to the
                                                                                  program as a string.
This is the prompt
        to the user.
                                                       This is the text field in which          If the user clicks
        This is the default value that                 the user types the value.                Cancel, the null value
        appears when the dialog                                                                 will be returned to the
        opens.                                                                                  program and no value
                                                                                                will be assigned to
                                                                                                the variable.
         Fig. 7.7 Prompt dialog displayed by the window object’s prompt method.
          “now” is a new instance of JavaScript
          native object Date. It can invoke all
welcome6.html
          the methods of that object class
    (1 of 3)
          Note that conversion to integer
          type was not needed when the
          value was returned by the getHours
          method
welcome6.html
    (2 of 3)
welcome6.html
    (3 of 3)