Thursday, March 23, 2017

JavaScript Note

# DOM - document  object model
# var oldvlaue = document.getElementById("myID").value; //Getting
# document.getElementById("myId").value = "new value"   //Setting

#<p id=“myID"></p>
<script>document.getElementById("myID").innerHTML= “Let’s Learn DOM”;</script>

#<script>
var x = document.getElementById("title");
document.getElementById("myID").innerHTML="The value of element is " + x.innerHTML;
</script>

# element.addEventListener(event, function, useCapture);

# <body>
<button id="myBtn">click</button>
<script>
document.getElementById("myBtn").addEventListener("click", hello);
function hello() {
alert ("Hello World!");
}
</script>
</body>




#element.addEventListener("mouseover", FunctionOne);
element.addEventListener("click", FunctionTwo);
element.addEventListener("click", FunctionThree);
element.addEventListener("mouseout", FunctionFour);

# <body>
<script>
document.write(Date());
</script>
</body>



# <head>
<title>DOM Sample 1</title>
</head>
<body>
Information about this document.<br>
<script type="text/javascript">
document.write("<br>Title: ",document.title);
document.write("<br>Referrer: ",document.referrer);
document.write("<br>Domain: ",document.domain);
document.write("<br>URL: ",document.URL);
</script>
</body>


#DOM Events

#<html>
<head>
<title>DOM Sample</title>

<script type="text/javascript">
function showInfo() {var element = document.getElementById("opener");
var buffer = element.id + " tag is " + element.tagName;
alert(buffer);
element = document.getElementById("actionItem");
buffer = element.id + " tag is " + element.tagName;
buffer += ", type is "+element.type;alert(buffer);}
</script>

</head>
<body>
<p id="opener">The id attribute is very helpful.</p>
<p id="closer">This is the closing paragraph.</p>
<form><button id="actionItem" type="button" onclick="showInfo()">Show Info</button></form>
</body>
</html>


# Creating elements through Nodes
•Steps
1.Create the element (element node)
2.Append it to an existing element


#The HTML Document Object Model is a standard for structuring data on a web page


#  javaScript  born bcse , some data  has to validate at client  side
#  3 parts dom-  document  object model  -- node, bom ,ecma script

# DOM - Nodes cn be removed , added , replaced and  modifed easily
        Developers cn alter the appearance and content of a web page without  reloading it

# BOM - browser  object model

# Two ways to use the <script> elemnet
  #put javascript code directly into  page  within 
   tags
  #Include  javascript from other  file

#<script>  alert("What you want  to  print"); </script>

# Including External JS files ,the  src attribute is required .
# <script  type ="text/javascript" src = "example.js"></script>

#<script> elemnet  using  src attribute should  not  include  additional javaScript
code between  the  js code between  the <script> and </script> tags . iT is  ignored

# <script  src = "example.js"></script>


# The main purpose of this <script>  format  was to keep  to external file references,
both css files and javaScript files , in the  same area

#Including  js  in  <head>  means  that all the js  code must  be  downloaded , interpreted 
before the page begins rendering

#<script  tag  in  body element>

#Any  images and stylesheets that  follow the script tag dont start downloading until  script
has finished  downloading and executing
#A defer external script  will  start  downloading immediately but wont execute until  after  the
page is  rendered.

#DEFERRED SCRIPTS >>>> purpose  of  defer  is  to  indicate  that  a  script won't be changing
 the structure  of  the  page as it  executes.
 internal  file  structe  not chnged  but  external  may be

#defer atttribute  ona  a <script>  element  signals to  the  browser ,that  download  should  begin
immediately  but  execution  should be  deferred.

#even  though  the  <script>  elements  are  included  in  the  documnet  <head>  they  will  not   be  executed
until  after the  browser  has  received the  closing </html> tag.

# <script  type = "text/javascript" defer src = "example.js"></script>
# scripts  will  be executed  in  the  order in  which  they  appear
<script  type = "text/javascript" defer = "defer" src = "example.js"></script>
# the  defer , async attribute is supported only for external script files.........
# All old  browsers  , they  will  ignore  defer , so  it  is   still best to
  put deferred scripts  at the bottom of the page .

# The async attribute is similar to  defer ,in that it changes the way the script is processed.
# async = "async"

# Asynchronous execution - html parsing may continue and script will  be
executed as soon as it its ready .
# asnc  order is nt guaranteed

# Asynchrous  scripts are guaranteed to execute before the page's
 load  event and may execute  before or after DOMContentLoaded

# <script type ="text/javascript"  src = "javascript.js" async = "async"></script>

# inline code  vs  external  code >>>internal  scripts  are great  but , it  is  best  to  include
javascript using   external files  is  used  bcse  maintainalbility , caching - if two pages  are
using the  same file , the file is downloaded only once (this cause to faster  page loading)


# js  in xhtml  file  prob  fix 1 -  not goood  way
  < greater  sign  dosent  know  it
  replace all  occurences  of  the  less than symbol < with  its  , html entity (&lt;)
  a &lt; b
 
  <script type ="text/javascript">
   function compare(a,b)
   {
        if(a &lt; b)
    {
        alert("A is less than B");
         }
   }
   </script>

# js  in xhtml file   fix 2
  Wrap  the  javaScript  code in  a  CDATA section

  in XHTML  or  xml  , CDATA  sections   are  used to
  indicate ares used  to  indicate areas of  the document
  that contain free- from text not intended  to be parsed.

   <script type ="text/javascript">
   <![CDATA[
   function compare(a,b)
   {
        if(a &lt; b)
    {
        alert("A is less than B");
         }
   }
  ]]> </script>

..........this  part  will  be  ignore  by  html  parser ,  but  will  execute  by javaScript
CDATA[
   function compare(a,b)
   {
        if(a &lt; b)
    {
        alert("A is less than B");
         }
   }
  ]

..........

# js in xhtml  issues
  some browsers  complaint  to works in  xhtml

  if browser dont  support  CDATA  sections, CDATA  markup must
  be offset  by  javaScript  commnets .
 That  foramt  works in  all  modern  browsers

 <script type ="text/javascript">
  // <![CDATA[
   function compare(a,b)
   {
        if(a &lt; b)
    {
        alert("A is less than B");
         }
   }
 // ]]>
</script>

#By  inculding JavaScript  using  external files , there's no need to  use the xhtml
or comment hacks mentioned  previously.

# JavaScript  comments  
  single  line comment   // 
  multiline comment      /*    */
# JavaScript is  case  sentitive
# typeof  is  a  key word in  javaScript , you cnt  use  it  as name  of  a function.

# identifier = name of a variable , function , property  or function  argument .
# identifier's  name first  character must  be  a  letter , _  or  $  sign . All other 
  character may be letters , underscores , dollar signs or numbers.Use  camal  case .For  First
  word first leter use simple letter . 
  eg:- numberOne
# Statements  in  ECMAScript are  terminated  by a  semicolon .
  ommiting  the   semicolon makes parser  determine  whether  the end of  a  statement  occurs
 .It  is  not  recommonded.
  Semicolons may improve performance because parsers  try to correct syntax errors by inserting
  semicolons where they appear  to be .

            

# document.write(samp_str + "<br/>");
  document.write("String  Variable  finally Length  is" + stringVar.length + "<br/>");
  document.write("String  Variable  substring  " + stringVar.substring(6,12) + "<br/>" );
  document.write("SFinal  letter" + stringVar.charAt(stringVar.length - 1)  + "<br/>");
  document.write("Index  of T is " + stringVar.indexOf('t') + "<br/>") ;

# String cant  be  multiplied  , if  you  try  to  multiply  number  and  string .
  then  javaScript  treated  that string  as to  number

 var str_var =  "5" ;
 var num_var =  6 ;

 var  total =  str_var +  num_var ; //56
 var  multiply =  str_var *  num_var ; //30
      total =  Number(str_var) +  num_var ; //11

 var num_var = String(num_var);

# var  folat_var  =  3.14156767877 ;
  var  floar_str  =  folat_var.toFixed(5); //3.14156
  document.write((round_num1 <= round_num2) + "<br/>") ;

# var vehicles =  new  Array("car","truck","van") ;
  document.write( vehicles[1] + "<br/>") ;


# for (i  in  vehicles)
   {
     document.write(vehicles[i] + "<br/>") ;
   }

# var  rand_var = (5 < 10) ? "5 is less than 10 ":"5 is greater than 10 " ;
# if (5> 10)
  {
    document.write("5 is  greater than 10" +  "<br/>")
  }
  else if(5<5)
  {
    document.write("5 is  greater than 5" +  "<br/>")
  }
  else
  {
    document.write("5 is less than 5" +  "<br/>")
  }


# var town= "Colombo" ;
  switch(town)
  {
   case "Galle"   :document.write("Town  is  Galle"+  "<br/>") ;break ;
   case "Colombo" :document.write("Town  is  Colombo"+  "<br/>") ;break ;
   default        :document.write("Town  is  not  defined"+  "<br/>") ;break ;
  }


#While  loop
 var count = 1 ;

 while(count <= 10)
 {

    if(count == 6 )
    {
        break ; // 2,4  will  be  print
    }
    if(count % 2 )
    {
        document.write(count + "<br/>") ;
                count ++ ;
    }
    document.write(count + "......"+ "<br/>") ;
                count ++ ;
 }

# //Do while  loop

 var  numThree  =  12 ;
 do
 {
    document.write("Inside Do " + numThree +  "</br>") ;
        numThree -- ;
 }
 while (numThree > 8 );


#  //For  LOop
  for(var num =  0 ; num < 11 ; num ++)
  {
    document.write( num  + "<br/>");
  }

# if  your  browser dont understand  javaScript
 <body>
 <script language="javascript" type ="text/javascript">
  <!---Hide javaScript
   function compare(a,b)
   {
        if(5>10)
    {
        alert("A is less than B");
         }
   }
  -->
</script>
<noscript>
    <h3>This site requires JavaScript</h3>
</noscript>
</body>


#  <script type="text/javascript" src="js/addFunction.js"></script>
   <!--Adding external javascript  file    -->

#  Function  we  dont  have  to  again  again  tasks
   //Created In another .js file
   function addingTwoNumbers(numOnee , numTwoo)
   {
    var  total = numOnee +  numTwoo ;
        return  total ;
   }

#  //Calling  function  from  the  external  javaScript  file.....Begin.....
   document.write( " Sum  of  7 and  9  is ..... = " + addingTwoNumbers(7 , 9 )) ;
 //Calling  function  from  the  external  javaScript  file.....End.......

 

####### Tutorial  Part 2 ######
# In header  tag
<head >
    <style>
          #h3style
        {
            color: gray;
        }
    </style>
</head>

#<body onResize ="changeImage();" onLoad = "alert('website Loaded');">

 <script language = "javascript" type ="text/javascript">
 <!-- Hide JavaScript

    function  changeImage()
        {
        document.getElementById("idImgSucess").style.height = "35%" ;
        document.getElementById("idImgSucess").style.width  = "35%" ;
                return   true ;
    }

    function alertMe()
    {
        alertMsg =  document.idImgSucess.src + "\nHeight: " + document.idImgSucess.height + "\nWidth: "
                            + document.idImgSucess.width ;

        alert(alertMsg) ;
        return  true    ;
        //Has error  of  TypeError: document.idImgSucess is undefined
    }

    function changeColor()
    {
        document.getElementById("h3style").style.color = "red" ;
         document.getElementById("h3style").firstChild.nodeValue = "Excited" ;
         return   true ;
    }

    function changeAgain()
        {
            document.getElementById("h3style").style.color = "gray" ;
            document.getElementById("h3style").firstChild.nodeValue = "Bored" ;
             return   true ;
        }

    function showParagraph()
        {
            document.getElementById("idFirstP").style.visiblity  = (document.formm.firstPara.checked)? "visible" :"hidden" ;
            document.getElementById("idSecondP").style.visiblity = (document.formm.secndPara.checked)?"visible" :"hidden" ;
            document.getElementById("idThirdP").style.visiblity  = (document.formm.thirdPara.checked)? "visible" :"hidden" ;
           
             return   true ;
        }


 -->
</script>
<noscript>
    <h3>This site requires JavaScript</h3>
</noscript>

 <img  src ="sccess.jpeg"  id = "idImgSucess" onClick= "alertMe();" onDblClick="alert('You Double Clicked');" />
 <h3  id = "h3style" onMouseOver = "changeColor();" onMouseOut = "changeAgain();">RollOver </h3>

<p id = "idFirstP">This is  a Paragraph </p>
<p id = "idSecondP">This is a Paragraph </p>
<p id = "idThirdP">This is  a Paragraph </p>

<form name = "formex">
    <input type = "checkbox" name = "firstPara"  onClick ="showParagraph();"/>
    <input type = "checkbox" name = "secndPara"  onClick ="showParagraph();"/>
    <input type = "checkbox" name = "thirdPara"  onClick ="showParagraph();"/>
</form>

<br/>
<br/>

<form name = "formex">
    <input type = "checkbox" name = "firstPara"  onClick ="showParagraph();"/>
    <input type = "checkbox" name = "secndPara"  onClick ="showParagraph();"/>
    <input type = "checkbox" name = "thirdPara"  onClick ="showParagraph();"/>
</form>


<form name = "formTwo">
    <p>Text Input </p>
    <input type = "text" name = "textInput" onBlur = "alert('onBlur Trigger');" onFocus ="alert('onFocus Triggered');"/>
   
</form>

</body>
</html>

####w3
# var person = "John Doe", carName = "Volvo", price = 200;
# var x = "5" + 2 + 3;
  If you put a number in quotes, the rest of the numbers will be treated as strings, and concatenated.
output  will  be 523
 var x = 2 + 3 + "5";
output  will  be 55


#  +=     x += y     x = x + y
   %=     x %= y     x = x % y 
   /=     x /= y     x = x / y


# JavaScript Comparison Operators

==     equal to
===     equal value and equal type
!=     not equal
!==     not equal value or not equal type
>     greater than
<     less than
>=     greater than or equal to
<=     less than or equal to
?     ternary operator


#JavaScript Logical Operators
Operator     Description
&&         logical and
||         logical or
!         logical not

#JavaScript     Type Operators
Operator     Description
typeof         Returns the type of a variable
instanceof     Returns true if an object is an instance of an object type

#JavaScript Bitwise Operators

Bit operators work on 32 bits numbers.
Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number.
Operator     Description         Example        Same as     Result        Decimal
&         AND             5 & 1            0101 & 0001     0001          1
|         OR             5 | 1            0101 | 0001     0101          5
~         NOT             ~ 5            ~0101     1010            10
^         XOR             5 ^ 1            0101 ^ 0001     0100           4
<<         Zero fill left shift     5 << 1     0101 << 1  1010              10
>>         Signed right shift     5 >> 1     0101 >> 1  0010               2
>>>         Zero fill right shift     5 >>> 1        0101 >>> 1     0010            2




The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return 11111111111111111111111111111010

Bitwise operators are fully described in the JS Bitwise chapter.

#Operand     Operator     Operand
100     +     50


###
JavaScript Operator Precedence Values
Value     Operator     Description     Example
19     ( )     Expression grouping     (3 + 4)
                 
18     .     Member     person.name
18     []     Member     person["name"]
                 
17     ()     Function call     myFunction()
17     new     Create     new Date()
                 
16     ++     Postfix Increment     i++
16     --     Postfix Decrement     i--
                 
15     ++     Prefix Increment     ++i
15     --     Prefix Decrement     --i
15     !     Logical not     !(x==y)
15     typeof     Type     typeof x
                 
14     *     Multiplication     10 * 5
14     /     Division     10 / 5
14     %     Modulo division     10 % 5
14     **     Exponentiation     10 ** 2
                 
13     +     Addition     10 + 5
13     -     Subtraction     10 - 5
                 
12     <<     Shift left     x << 2
12     >>     Shift right     x >> 2
12     >>>     Shift right (unsigned)     x >>> 2
                 
11     <     Less than     x < y
11     <=     Less than or equal     x <= y
11     >     Greater than     x > y
11     >=     Greater than or equal     x >= y
                 
10     ==     Equal     x == y
10     ===     Strict equal     x === y
10     !=     Unequal     x != y
10     !==     Strict unequal     x !== y
                 
6     &&     Logical and     x && y
5     ||     Logical or     x || y
                 
3     =     Assignment     x = y
3     +=     Assignment     x += y
3     -=     Assignment     x -= y
3     *=     Assignment     x *= y
3     %=     Assignment     x %= y
3     <<=     Assignment     x <<= y
3     >>=     Assignment     x >>= y
3     >>>=     Assignment     x >>>= y
3     &=     Assignment     x &= y
3     ^=     Assignment     x ^= y
3     |=     Assignment     x |= y

Pale red entries indicates experimental or proposed technology (ECMASScript 2016 or ES7)

Expressions in parentheses are fully computed before the value is used in the rest of the expression.

## JavaScript Data Types

JavaScript variables can hold many data types: numbers, strings, objects and more:
var length = 16;                               // Number
var lastName = "Johnson";                      // String
var x = {firstName:"John", lastName:"Doe"};    // Object


#JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

var x;               // Now x is undefined
var x = 5;           // Now x is a Number
var x = "John";      // Now x is a String

# Strings are written with quotes. You can use single or double quotes:

#  var y = 123e5;      // 12300000
   var z = 123e-5;     // 0.00123

# Booleans can only have two values: true or false.
    var x = true;
    var y = false;
#JavaScript arrays are written with square brackets.
var cars = ["Saab", "Volvo", "BMW"];

# JavaScript objects are written with curly braces.

Object properties are written as name:value pairs, separated by commas.
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

# You can use the JavaScript typeof operator to find the type of a JavaScript variable.
The typeof operator returns the type of a variable or an expression:

typeof ""                  // Returns "string"
typeof "John"              // Returns "string"
typeof "John Doe"          // Returns "string"



#The typeof operator can return one of these primitive types:

    string
    number
    boolean
    null
    undefined


# The typeof operator can return one of two complex types:

    function
    object

Example
typeof [1,2,3,4]             // Returns "object" (not "array", see note below)
typeof {name:'John', age:34} // Returns "object"
typeof function myFunc(){}   // Returns "function"


The typeof operator returns "object" for arrays because in JavaScript arrays are objects.

# Unfortunately, in JavaScript, the data type of null is an object.
  You can empty an object by setting it to null:
  var person = null;         // Value is null, but type is still an object



#Difference Between Undefined and Null
typeof undefined           // undefined
typeof null                // object
null === undefined         // false
null == undefined          // true




#Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};


# <script>
  var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
  document.getElementById("demo").innerHTML =
  person.firstName + " is " + person.age + " years old.";

 </script>



#HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from being submitted:

<form action="/action_page_post.php" method="post">
  <input type="text" name="fname" required>
  <input type="submit" value="Submit">
</form>

##
Validation can be defined by many different methods, and deployed in many different ways.
Server side validation is performed by a web server, after input has been sent to the server.
Client side validation is performed by a web browser, before input is sent to a web server.

#HTML5 introduced a new HTML validation concept called constraint validation.

HTML constraint validation is based on:

    Constraint validation HTML Input Attributes
    Constraint validation CSS Pseudo Selectors
    Constraint validation DOM Properties and Methods

#Constraint Validation HTML Input Attributes
Attribute     Description
disabled     Specifies that the input element should be disabled
max         Specifies the maximum value of an input element
min         Specifies the minimum value of an input element
pattern     Specifies the value pattern of an input element
required     Specifies that the input field requires an element
type          Specifies the type of an input element


#The typeof operator can return one of these primitive types:

    string
    number
    boolean
    null
    undefined
typeof "John"              // Returns "string"
typeof 3.14                // Returns "number"
typeof true                // Returns "boolean"
typeof false               // Returns "boolean"

#The typeof operator can return one of two complex types:

    function
    object
typeof [1,2,3,4]             // Returns "object" (not "array", see note below)
typeof {name:'John', age:34} // Returns "object"
typeof function myFunc(){}   // Returns "function"

The typeof operator returns "object" for arrays because in JavaScript arrays are objects.

# var person;                // Value is undefined, type is undefined

#Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different results.

    function toCelsius(fahrenheit) {
        return (5/9) *  (fahrenheit-32);
    }
    document.getElementById("demo").innerHTML = toCelsius(77);


#In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:

All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.

#Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"};

#Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.


#<p id="demo"></p>

<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
document.getElementById("demo").innerHTML = person.firstName + " is " + person.age + " years old.";
</script>


#You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]


# objectName.methodName()


#Do Not Declare Strings, Numbers, and Booleans as Objects!

When a JavaScript variable is declared with the keyword "new", the variable is created as an object:
var x = new String();        // Declares x as a String object
var y = new Number();        // Declares y as a Number object
var z = new Boolean();       // Declares z as a Boolean object

Avoid String, Number, and Boolean objects. They complicate your code and slow down execution speed.


#In JavaScript, objects and functions are also variables.
 In JavaScript, scope is the set of variables, objects, and functions you have access to.
 JavaScript has function scope: The scope changes inside functions.

# Local variables are created when a function starts, and deleted when the function is completed.

# A variable declared outside a function, becomes GLOBAL.
A global variable has global scope: All scripts and functions on a web page can access it.


#If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable.

This code example will declare a global variable carName, even if the value is assigned inside a function.

#

No comments:

Post a Comment

The AI Driven Software Developer, Optimize Innovate Transform

  The AI-Driven Software Developer: Optimize, Innovate, Transform": AI Transformation in Software Development : Understand how AI is re...