Monday, June 8, 2015

Javascript tutorial 2



Adding Methods to JavaScript Objects

Methods are just functions attached to objects.
Defining methods to an object is done inside the constructor function:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;

this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
The changeName() function assigns the value of name to the person's lastname property.
<!DOCTYPE html><body><script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.changeName=changeName;
function changeName(name)
{
this.lastname=name;
}
}
myMother=new person("Sally","Rally",48,"green");
myMother.changeName("Doe");
document.write(myMother.lastname);
</script></body></html>
JavaScript knows which person you are talking about by "substituting" this with myMother.

JavaScript Classes

JavaScript is an object oriented language, but JavaScript does not use classes.
In JavaScript you don’t define classes and create objects from these classes (as in most other object oriented languages).
JavaScript is prototype based, not class based.

JavaScript for...in Loop

The JavaScript for...in statement loops through the properties of an object.

Syntax

for (variable in object)
  {
  code to be executed
  }
Note: The block of code inside of the for...in loop will be executed once for each property.
Looping through the properties of an object:
<!DOCTYPE html><html><body>
<p>Click the button to loop through the properties of an object named "person".</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
document.getElementById("demo").innerHTML=txt;
}
</script></body></html>

JavaScript Numbers

JavaScript numbers can be written with, or without decimals:
Extra large or extra small numbers can be written with scientific (exponent) الاس notation:

Example

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

JavaScript Numbers are 64-bit Floating Point

JavaScript is not a typed language. Unlike many other programming languages, it does not define different types of numbers, like integers, short, long, floating-point etc.
JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard.
This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63:

Precision

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.
The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate:

Octal ثماني and Hexadecimal عشري

JavaScript interprets numeric constants as octal if they are preceded by a zero, and as hexadecimal if they are preceded by a zero and "x".
Never write a number with a leading zero, unless you want an octal conversion.
By default, Javascript displays numbers as base 10 decimals.
But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary).
<script>
var myNumber = 128;
document.write(myNumber + ' decimal<br>');
document.write(myNumber.toString(16) + ' hex<br>');
document.write(myNumber.toString(8) + ' octal<br>');
document.write(myNumber.toString(2) + ' binary<br>');
</script>

Infinity

If you calculate a number outside the largest number provided by Javascript, Javascript will return the value of Infinity or -Infinity (positive or negative overflow):
<script>
myNumber=2;
while (myNumber!=Infinity)
{
myNumber=myNumber*myNumber;
document.write(myNumber +'<BR>');
}
</script>
Division by 0 (zero) also generates Infinity:

NaN - Not a Number

NaN is JavaScript reserved word indicating that the result of a numeric operation was not a number.
You can use the global JavaScript function isNaN(value) to find out if a value is a number.
<script>
var x = 1000 / "Apple";
var y = 1000 / "1000";
document.getElementById("demo").innerHTML = isNaN(x) + "<br>" + isNaN(y);
</script>
Result will be true then false.

Numbers Can be Numbers or Objects

JavaScript numbers can be primitive بدائي values created from literals, like var x = 123;
JavaScript number can also be objects created with the new keyword, like var y = new Number(123);
<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
var txt = typeof(x) + " " + typeof(y);
document.getElementById("demo").innerHTML=txt;
</script>
Notes: typeof() define the type of variables;
Normally, because of some nasty side effects, you will not define numbers as objects.
<script>
var x = 123;              // x is a number
var y = new Number(123);  // y is an object
document.getElementById("demo").innerHTML = x===y;
</script>
Result: false

Number Properties

  • MAX_VALUE - MIN_VALUE - NEGATIVE_INFINITY -  POSITIVE_INFINITY – NaN – prototype -  constructor
All number properties are properties of JavaScripts' number object wrapper called Number. These properties can only be accesses as Number.MAX_VALUE. Using num.MAX_VALUE, where num is a created object or a primitive number value, will return undefined.

Number Methods

  • toExponential()
  • toFixed()
  • toPrecision()
  • toString()
  • valueOf()
Note: Primitive values, like 3.14, cannot have properties and methods (because they are not objects).
With JavaScript, all methods of the number object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods.

 JavaScript Strings

A string simply stores a series of characters like "John Doe". You can use single or double quotes:

Example

var carname="Volvo XC60";
var carname='Volvo XC60';
You can access each character in a string with its position (index):

 Example

var character=carname[7];
 String indexes are zero-based, which means the first character is [0], the second is [1], and so on.
you can put quotes inside a string by using the \ escape character before the apostrophe :

Example

var answer='It\'s alright';
var answer="He is called \"Johnny\"";

String Length

The length of a string (a string object) is found in the built in property length:
var txt="Hello World!";
document.write(txt.length);
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);

 Finding a String in a String

The indexOf() method returns the position (as a number) of the first found occurrence of a specified text inside a string:
 <script>
function myFunction()
{
var str=document.getElementById("p1").innerHTML;
var n=str.indexOf("welcome ");
document.getElementById("p2").innerHTML=n+1;
}
</script>
The method returns -1 if the specified text is not found.
The lastIndexOf() method starts searching at the end of the string instead of at the beginning.

Matching Content

The match() method can be used to search for a matching content in a string:
<!DOCTYPE html>
<html>
<body>
<script>
var str="Hello world!";
document.write(str.match("world") + "<br>");
document.write(str.match("World") + "<br>");
document.write(str.match("world!"));
</script>
</body>
</html>

Replacing Content

The replace() method replaces a specified value with another value in a string.

Example

str="Please visit Microsoft!"
var n=str.replace("Microsoft","W3Schools");

Upper Case and Lower Case

A string is converted to upper/lower case with the methods toUpperCase() / toLowerCase():

Example

var txt="Hello World!";       // String
var txt1=txt.toUpperCase();   // txt1 is txt converted to upper
var txt2=txt.toLowerCase();   // txt2 is txt converted to lower

Convert a String to an Array

A string is converted to an array with the built in method string.split():
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display the array values after the split.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str="a,b,c,d,e,f";
var n=str.split(",");
document.getElementById("demo").innerHTML=n[0];
}
</script></body>

Special Characters

The backslash (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string.
Look at the following JavaScript code:
var txt="We are the so-called "Vikings" from the north.";
document.write(txt);
In JavaScript, a string is started and stopped with either single or double quotes. This means that the string above will be chopped to: We are the so-called To solve this problem, you must place a backslash (\) before each double quote in "Viking". This turns each double quote into a string literal:
var txt="We are the so-called \"Vikings\" from the north.";
document.write(txt);
JavaScript will now output the proper text string: We are the so-called "Vikings" from the north.
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

Strings Can be Strings or Objects

JavaScript strings can be primitive values created from literals, like var x = "John";
JavaScript strings can also be objects created with the new keyword, like var y = new String("John");

Example

var x = "John";
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object
Normally, because of some nasty side effects, you will not define strings as objects.

Example

var x = "John";             
var y = new String("John");
(x === y) // is false because x is a string and y is an object.
Note: Primitive values, like "John", cannot have properties or methods (because they are not objects).
With JavaScript, all methods and properties of the string object are also available to primitive values, because Javascript will temporarily transfer primitive values to objects before executing the methods or properties.

String Properties and Methods

Properties:
  • length
  • prototype
  • constructor
Methods:
  • charAt() - charCodeAt() - concat() - fromCharCode() - indexOf() - lastIndexOf() - localeCompare() - match() - replace() - search() - slice() - split() - substr() - substring() - toLowerCase() - toUpperCase() - toString() - trim()  - valueOf()

JavaScript Date Object

The Date object is used to work with dates and times.
To show today:
var d=new Date();
document.write(d);
To show full year:
function myFunction()
{
var d = new Date();
var x = document.getElementById("demo");
x.innerHTML=d.getFullYear();
}
getTime() getTime() returns the number of milliseconds since 01.01.1970.
setFullYear() How to use setFullYear() to set a specific date.
toUTCString() use toUTCString() to convert today's date (according to UTC) to a string.
getDay() Use getDay() and an array to write a weekday, and not just a number.
function myFunction()
{
var d = new Date();
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";

var x = document.getElementById("demo");
x.innerHTML=weekday[d.getDay()];
}
Display a clock
How to display a clock on your web page.
function startTime()
{
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout(function(){startTime()},500);
}

function checkTime(i)
{
if (i<10)
  {
  i="0" + i;
  }
return i;
}

Create a Date Object

The Date object is used to work with dates and times. & created with the Date() constructor.
There are four ways of initiating a date:
new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Most parameters above are optional. Not specifying, causes 0 to be passed in.
Once a Date object is created, a number of methods allow you to operate on it. Most methods allow you to get and set the year, month, day, hour, minute, second, and milliseconds of the object, using either local time or UTC (universal, or GMT) time.
All dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC) with a day containing 86,400,000 milliseconds.
Some examples of initiating a date:
var today = new Date()
var d1 = new Date("October 13, 1975 11:13:00")
var d2 = new Date(79,5,24)
var d3 = new Date(79,5,24,11,33,0)

Set Dates

We can easily manipulate the date by using the methods available for the Date object.
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);
And 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 5 days to date shifts the month or year, the changes are handled auto by the Date object itself!

Compare Two Dates

Date object is also used to compare 2 dates. this example compares today's date with the 14th January 2100:
var x=new Date();
x.setFullYear(2100,0,14);
var today = new Date();
if (x>today)
  {
  alert("Today is before 14th January 2100");
  }
else
  {
  alert("Today is after 14th January 2100");
  }

JavaScript Array Object

The Array object is used to store multiple values in a single variable.
var i;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (i=0;i<mycars.length;i++)
{
document.write(mycars[i] + "<br>");
}
You will find more examples at the bottom of this page.

What is an Array?

An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:
var car1="Saab";
var car2="Volvo";
var car3="BMW";
However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you can access the values by referring to an index number.

Create an Array

An array can be created in three ways.
The following code creates an Array object called myCars:
1: Regular:
var myCars=new Array();
myCars[0]="Saab";      
myCars[1]="Volvo";
myCars[2]="BMW";
2: Condensed:
var myCars=new Array("Saab","Volvo","BMW");
3: Literal:
var myCars=["Saab","Volvo","BMW"];

Access an Array

You refer to an element in an array by referring to the index number.
This statement access the value of the first element in myCars:
var name=myCars[0];
This statement modifies the first element in myCars:
myCars[0]="Opel";
[0] is the first element in an array. [1] is the second . . . . . (indexes start with 0)

You Can Have Different Objects in One Array

All JavaScript variables are objects. Array elements are objects. Functions are objects.
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;

Array Methods and Properties

The Array object has predefined properties and methods:
var x=myCars.length             // the number of elements in myCars
var y=myCars.indexOf("Volvo")   // the index position of "Volvo"

JavaScript Math Object

The Math object allows you to perform mathematical tasks.
round()
function myFunction()
{
document.getElementById("demo").innerHTML=Math.round(2.5);
}
Result 3
Math.random();
max()
function myFunction()
{
document.getElementById("demo").innerHTML=Math.max(5,10);
}
Math.min (5,10);

Math Object

The Math object allows you to perform mathematical tasks. It includes several mathematical constants and methods.
Syntax for using properties/methods of Math:
var x=Math.PI;
var y=Math.sqrt(16);
Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it. uses the floor() and random() methods of the Math object to return a random number between 0 and 10:
document.write(Math.floor(Math.random()*11));
The code above can result in the following output:
8

JavaScript RegExp Object

RegExp, is short for regular expression.

RegExp Object

A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform 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.

RegExp Modifiers

Modifiers are used to perform case-insensitive and global searches.
The i modifier is used to perform case-insensitive matching.
The g modifier is used to perform a global match (find all matches rather than stopping after the first match).
Do a case-insensitive search for "w3schools" in a string:
var str="Visit W3Schools";
var patt1=/w3schools/i;
<body>
<p id="demo">Click the button to do a case-insensitive search for "w3schools" in a string.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var str = "Visit W3Schools";
var patt1 = /w3schools/i;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>
My code:
I have 2 files one html another js
Html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="srch.js"></script>
Search For: <input type="text" id="mysrch" />
<button onclick="mysearch()">Search</button>
<form name="myform" action="#" method="post">
<textarea id="txt" row="10" cols="50">
Hello World I love you Javascript, i love you
</textarea>
</form>
</body>
</body>
Javascript file which I will call it from html file
function mysearch()
{
var x=document.getElementById("mysrch").value;
var y=document.getElementById("txt").value;

var result=y.match(x);
if (result)
{
            alert ("Yes! we found " + result);
}
else
{
            alert ("Sorry Dear neto");
}
}
Do a global search for "is":
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to do a global search for "is" in a string.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
var str = "Is this all there is?";
var patt1 = /is/g;
var result = str.match(patt1);
document.getElementById("demo").innerHTML=result;
}
</script>

</body>
</html>
Result : is,is
Do a global, case-insensitive search for "is":
var str="Is this all there is?";
var patt1=/is/gi;

test()

The test() method searches a string for a specified value, and returns true or false, depending on the result.
The following example searches a string for the character "e":

Example

var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are free"));
Since there is an "e" in the string, the output of the code above will be: true
note: to do new line inside alert + '\n' +
Example:
function mysearch()
{
var x=document.getElementById("mysrch").value;
var y=document.getElementById("txt").value;
var mytext = new RegExp(x);
var result=y.match(x);
var t=mytext.test(y);
if (result)
{
            alert ("Yes! we found " + result + '\n' + " The Test of Search " + t );
}
else
{
            alert ("Sorry Dear neto");
}
}

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.
The following example searches a string for the character "e":
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are free"));

JavaScript HTML DOM

With the HTML DOM, JavaScript can access all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
With a programmable object model, JavaScript gets all the power it needs to create dynamic HTML:
  • JavaScript can change all the HTML elements in the page
  • JavaScript can change all the HTML attributes in the page
  • JavaScript can change all the CSS styles in the page
  • JavaScript can react to all the events in the page

What is the DOM?

The DOM is a W3C (World Wide Web Consortium اتحاد) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
  • Core DOM - standard model for all document types
  • XML DOM - standard model for XML documents
  • HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It defines:
  • The HTML elements as objects
  • The properties of all HTML elements
  • The methods to access all HTML elements
  • The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
  • Finding HTML elements by id
  • Finding HTML elements by tag name
  • Finding HTML elements by class name
  • Finding HTML elements by HTML object collections

Finding HTML Elements by Id

The easiest way to find HTML elements in the DOM, is by using the element id.
This example finds the element with id="intro":
<!DOCTYPE html>
<body>
<p id="intro">Hello World!</p>
<p>This example demonstrates the <b>getElementById</b> method!</p>
<script>
x=document.getElementById("intro");
document.write("<p>The text from the intro paragraph: " + x.innerHTML + "</p>");
</script></body></html>
If the element is found, the method will return the element as an object (in x).
If the element is not found, x will contain null.

Finding HTML Elements by Tag Name

This example finds the element with id="main", and then finds all <p> elements inside "main":
<body>
<p>Hello World!</p>
<div id="main">
<p>The DOM is very useful.</p>
<p>This example demonstrates the <b>getElementsByTagName</b> method</p>
</div>
<script>
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
document.write('First paragraph inside "main" is ' + y[0].innerHTML);
</script></body>

Finding HTML Elements by Class Name

If you want to find all HTML elements with the same class name. Use this method:
document.getElementsByClassName("intro");
The example above returns a list of all elements with class="intro".
Finding elements by class name does not work in Internet Explorer 5,6,7, and 8.

Finding HTML Elements by HTML Object Collections

This example finds the form element with id="frm", in the forms collection, and displays all element values:
<body>
<form id="frm1" action="form_action.asp">
  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>
var x=document.getElementById("frm1");
for (var i=0;i<x.length;i++)
  {
  document.write(x.elements[i].value);
  document.write("<br>");
  }
</script>
</body>
The following HTML object collections are accesible:
·         document.anchors - document.forms - document.images - document.links –
document.images

<body>
<img border="0" src="klematis.jpg" width="150" height="113">
<img border="0" src="klematis2.jpg" width="152" height="128">
<p>Number of images:
<script>
document.write(document.images.length);
</script></p>
</body>
Document.anchor

<body>
<a name="html">HTML Tutorial</a><br>
<a name="css">CSS Tutorial</a><br>
<a name="xml">XML Tutorial</a><br>
<p>Number of anchors:
<script>
document.write(document.anchors.length);
</script>
</p>
</body>
Result will be: Number of anchors: 3

Document.link
<html>
<body>
<img src ="planets.gif" width="145" height="126" alt="Planets" usemap ="#planetmap">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" href="sun.htm" alt="Sun">
<area shape="circle" coords="90,58,3" href="mercur.htm" alt="Mercury">
<area shape="                                                                                                                                                                  circle" coords="124,58,8" href="venus.htm" alt="Venus">
</map>
<p><a href="/js/">JavaScript Tutorial</a></p>
<p>Number of areas/links:
<script>
document.write(document.links.length);
</script></p>
</body>
</html>
The output of the code above will be: Number of areas/links: 4

Changing the HTML Output Stream

JavaScript can create dynamic HTML content:
Date: Wed Nov 06 2013 17:24:22 GMT+0200 (Egypt Standard Time)
In JavaScript, document.write() can be used to write directly to the HTML output stream:
<script>
document.write(Date());
</script>
Never use document.write() after the document is loaded. It will overwrite the document.

Changing HTML Content

The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
document.getElementById(id).innerHTML=new HTML
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
This example changes the content of an <h1> element:
<h1 id="header">Old Header></h1>
<script>
document.getElementById("header").innerHTML="New Header";
</script>
Example explained:
  • The HTML document above contains an <h1> element with id="header"
  • We use the HTML DOM to get the element with id="header"
  • A JavaScript changes the content (innerHTML) of that element

Changing the Value of an Attribute

document.getElementById(id).attribute=new value
This example changes the value of the src attribute of an <img> element:
<body>
<button onclick="myimage()">Change Image</button>
<img src="../2.jpg" id="myimg">
<script>
function myimage()
{
                document.getElementById("myimg").src="../1.jpg";
}
</script>
</body>
Example explained:
  • The HTML document above contains an <img> element with id="image"
  • We use the HTML DOM to get the element with id="image"
  • A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"

JavaScript HTML DOM - Changing CSS

Changing HTML Style

To change the style of an HTML element, use this syntax:
document.getElementById(id).style.property=new style
The following example changes the style of a <p> element:
document.getElementById("p1").style.color="blue";

Using Events

The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
  • An element is clicked on
  • The page has loaded
  • Input fields are changed
This example changes the style of the HTML element with id="id1", when the user clicks a button:
<body>
<button onclick="document.getElementById('p1').style.color='red'">Color</button>
<button onclick="document.getElementById
('p1').style.visibility='hidden'">Hide</button>
<button onclick="document.getElementById
('p1').style.visibility='visible'">Show</button>
<p id="p1">Hello World HTML DOM can change the style of paragraph CSS</p>
</body>
The Style object property categories:
To change the Background Image:
<head>
<script>
function displayResult()
{
document.body.style.background="#f3f3f3 url('img_tree.png') no-repeat right top";
}
</script>
</head>
<body>
<h1>Hello World!</h1>
<br>
<button type="button" onclick="displayResult()">Set background</button>
</body>

JavaScript HTML DOM Events

Examples of HTML events:
  • When a user clicks the mouse
  • When a web page has loaded
  • When an image has been loaded
  • When the mouse moves over an element
  • When an input field is changed
  • When an HTML form is submitted
  • When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
In this example, a function is called from the event handler:
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
To show date by using the even inside the element button
<button onclick="document.getElementById('p2').innerHTML=Date()">Date</button>
<body>
<p>Click the button to execute the <em>displayDate()</em> function.</p>
<button id="myBtn">Try it</button>
<script>
document.getElementById("myBtn").onclick=function(){displayDate()};
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
<p id="demo"></p>
</body>
In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
The function will be executed when the button is clicked.

The onload and onunload Events

The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. The onload and onunload events can be used to deal with cookies.

Example

<body onload="checkCookies()">
<script>
function checkCookies()
{
if (navigator.cookieEnabled==true)
            {
            alert("Cookies are enabled")
            }
else
            {
            alert("Cookies are not enabled")
            }
}
</script>
<p>An alert box should tell you if your browser has enabled cookies or not.</p>
</body>

The onchange Event

The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.
<head>
<script>
function myFunction()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
</script>
</head>
<body>
Enter your name: <input type="text" id="fname" onchange="myFunction()">
<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
</body>

The onmouseover and onmouseout Events

onmouseover & onmouseout events used to trigger a function when the user mouses over, or out of an HTML element.

The onmousedown, onmouseup and onclick Events

The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
<body>
<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="background-color:#D94A38;width:90px;height:20px;padding:40px;">Click Me</div>
<script>
function mDown(obj)
{
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="Release Me"
}
function mUp(obj)
{
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You"
}
</script>
</body>
Onfocus event:
<head>
<script>
function myFunction(x)
{
x.style.background="yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
</body>

JavaScript HTML DOM Navigation

With the HTML DOM, you can navigate the node tree using node relationships.

Navigating Node Relationships

The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships. Parent nodes have children.
  • In a node tree, the top node is called the root (or root node)
  • Every node has exactly one parent, except the root (which has no parent)
  • A node can have any number of children
  • Siblings are nodes with the same parent (brothers or sisters)
The following image illustrates a part of the node tree and the relationship between the nodes:
<html>
  <head>
    <title>DOM Tutorial</title>
  </head>
  <body>
    <h1>DOM Lesson one</h1>
    <p>Hello world!</p>
  </body>
</html>
 From the HTML above:
  • The root node <html> has no parents
  • The parent node of the <head> and <body> nodes is the <html> node
  • The parent node of the "Hello world!" text node is the <p> node
and:
  • The <html> node has two child nodes: <head> and <body>
  • The <head> node has one child node: the <title> node
  • The <title> node also has one child node: the text node "DOM Tutorial"
  • The <h1> and <p> nodes are siblings and child nodes of <body>
and:
  • The <head> element is the first child of the <html> element
  • The <body> element is the last child of the <html> element
  • The <h1> element is the first child of the <body> element
  • The <p> element is the last child of the <body> element
You can use the node properties like parentNode, firstChild, and lastChild, to navigate in an HTML document structure.

Warning !

A common error in DOM processing is to expect an element node to contain text.
In this example: <title>DOM Tutorial</title>, the element node <title> does not contain text. It contains a text node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property, or the nodeValue.

Child Nodes and Node Values

In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following code gets the value of the <p> element with id="intro":
<body>
<p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial we use the innerHTML property. However, learning the method above is useful for understanding the tree structure and the navigation of the DOM.
Using the firstChild property is the same as using childNodes[0]:
<body>
<p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").firstChild.nodeValue;
document.write(txt);
</script>
</body>

DOM Root Nodes

There are two special properties that allow access to the full document:
  • document.documentElement - The full document
  • document.body - The body of the document
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>

JavaScript HTML DOM Elements (Nodes)

Adding and Removing Nodes (HTML Elements)

Creating New HTML Elements (Nodes)

To add a new element to the HTML DOM, create element node first, and then append it to an existing element.
<body>
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script></body>

Example Explained  This code creates a new <p> element:

var para=document.createElement("p");
To add text to the <p> element, you must create a text node first. This code creates a text node:
var node=document.createTextNode("This is a new paragraph.");
Then you must append the text node to the <p> element:
para.appendChild(node);
Finally you must append the new element to an existing element.
This code finds an existing element:
var element=document.getElementById("div1");
This code appends the new element to the existing element:
element.appendChild(para);

Removing Existing HTML Elements

To remove an HTML element, you must know the parent of the element:

Example

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>

Example Explained 

This HTML document contains a <div> element with two child nodes (two <p> elements):
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
var parent=document.getElementById("div1");
Find the <p> element with id="p1":
var child=document.getElementById("p1");
Remove the child from the parent:
parent.removeChild(child);
It would be nice to be able to remove an element without referring to the parent.
But sorry. The DOM needs to know both the element you want to remove, and its parent
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
var child=document.getElementById("p1");
child.parentNode.removeChild(child);

HTML DOM Node List

The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code selects all <p> nodes in a document:
var x=document.getElementsByTagName("p");
The nodes can be accessed by index number. To access the second <p> you can write:
<body>
<p>Hello World!</p>
<p>The DOM is very useful!</p>
<script>
x=document.getElementsByTagName("p");
document.write("The innerHTML of the second paragraph is: " + x[1].innerHTML);
</script>
</body>

HTML DOM Node List Length

The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:
<body>

<p>Hello World!</p>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>length</b> property.</p>
<script>
x=document.getElementsByTagName("p");
for (i=0;i<x.length;i++)
  {
  document.write(x[i].innerHTML);
  document.write("<br>");
  }
</script>
</body>
Example explained:
  1. Get all <p> element nodes
  2. For each <p> element, output the value of its text node

JavaScript Window - The Browser Object Model

The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.

The Browser Object Model (BOM)

There are no official standards for the Browser Object Model (BOM).
Since modern browsers have implemented (almost) the same methods and properties for JavaScript interactivity, it is often referred to, as methods and properties of the BOM.

The Window Object

The window object is supported by all browsers. It represent the browser's window.
All global JavaScript objects, functions, and variables automatically become members of the window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");

Window Size

Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
  • window.innerHeight - the inner height of the browser window
  • window.innerWidth - the inner width of the browser window
For Internet Explorer 8, 7, 6, 5:
  • document.documentElement.clientHeight
  • document.documentElement.clientWidth
  • or
  • document.body.clientHeight
  • document.body.clientWidth
A practical JavaScript solution (covering all browsers):
<body>
<p id="demo"></p>
<script>
var w=window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h=window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

x=document.getElementById("demo");
x.innerHTML="Browser inner window width: " + w + ", height: " + h + "."
</script>
</body>
The example displays the browser window's height and width: (NOT including toolbars/scrollbars)

Other Window Methods

Some other methods:
  • window.open() - window.close() - window.moveTo() - window.resizeTo()
<html>
<head>
<script>
function open_win()
{
window.open("http://www.w3schools.com");
}
</script>
</head>

<body>
<form>
<input type="button" value="Open Window" onclick="open_win()">
</form>
</body>
</html>

JavaScript Window Screen

The window.screen object can be written without the window prefix.
Some properties:
  • screen.availWidth - available screen width
  • screen.availHeight - available screen height

Window Screen Available Width

The screen.availWidth property returns the width of the visitor's screen, in pixels, minus interface features like the Windows Taskbar.
<script>
document.write("Available Width: " + screen.availWidth);
</script>

JavaScript Window Location

Window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
The window.location object can be written without the window prefix.
Some examples:
  • location.hostname returns the domain name of the web host
  • location.pathname returns the path and filename of the current page
  • location.port returns the port of the web host (80 or 443)
  • location.protocol returns the web protocol used (http:// or https://)

Window Location Href: The location.href property returns the URL of the current page.

<script>
document.write(location.href);
</script>

Window Location Pathname

The location.pathname property returns the path name of a URL.
<script>
document.write(location.pathname);
</script>
The output of the code above is:      /js/js_window_location.asp

Window Location Assign: The location.assign() method loads a new document.

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

JavaScript Window History

The window.history object contains the browsers history. Can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript can access this object.
Some methods:
  • history.back() - same as clicking back in the browser - history.forward() - same as clicking forward in the browser
The history.back() method loads the previous URL in the history list.
This is the same as clicking the Back button in the browser. Create a back button on a page:
<head>
<script>
function goBack()
  {
  window.history.back()
  }
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
The output of the code above will be:
The same will be for forward
function goForward()
  {
  window.history.forward()
  }

JavaScript Window Navigator

The window.navigator object contains information about the visitor's browser.
The window.navigator object can be written without the window prefix.
<body>
<div id="example"></div>
<script>

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>Browser Language: " + navigator.language + "</p>";
txt+= "<p>Browser Online: " + navigator.onLine + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";

document.getElementById("example").innerHTML=txt;
</script>
</body>

Warning !!!

The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
  • The navigator data can be changed by the browser owner - Some browsers misidentify themselves to bypass site tests
  • Browsers cannot report new operating systems, released later than the browser

Browser Detection

Since the navigator object can be misleading about browser detection, using object detection can be used to sniff out different browsers.
Since different browsers support different objects, you can use objects to detect browsers. For example, since only Opera supports the property "window.opera", you can use that to identify Opera.
Example: if (window.opera) {...some action...}

JavaScript Popup Boxes

Confirm Box

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.
<body>
<p>Click the button to display a confirm box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var r=confirm("Press a button!");
if (r==true)
  {
  x="You pressed OK!";
  }
else
  {
  x="You pressed Cancel!";
  }
document.getElementById("demo").innerHTML=x;
}
</script></body>

Prompt Box

often used if you want the user to input a value before entering a page. When 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.
window.prompt("sometext","defaultvalue");
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
  {
  x="Hello " + person + "! How are you today?";
  document.getElementById("demo").innerHTML=x;
  }
}
</script>
</body>


JavaScript Timing Events

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.
It's very easy to time events in JavaScript. The two key methods that are used are:
  • setInterval() - executes a function, over and over again, at specified time intervals
  • setTimeout() - executes a function, once, after waiting a specified number of milliseconds
Note: The setInterval() and setTimeout() are both methods of the HTML DOM Window object.

The setInterval() Method

The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.

Syntax

window.setInterval("javascript function",milliseconds);
The window.setInterval() method can be written without the window prefix. The first parameter of setInterval() should be a function. The second parameter indicates the length of the time-intervals between each execution.
Note: There are 1000 milliseconds in one second.

Example: Alert "hello" every 3 seconds:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<p>After clicking away the alert box, an new alert box will appear in 3 seconds. This goes on forever...</p>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
setInterval(function(){alert("Hello")},3000);
}
</script>

</body>
</html>
The example show you how the setInterval() method works, but it is not very likely that you want to alert a message every 3 seconds.
Below is an example that will display the current time. The setInterval() method is used to execute the function once every 1 second, just like a digital watch.
<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>
<p id="demo"></p>

<script>
var myVar=setInterval(function(){myTimer()},1000);

function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
</script>

</body>
</html>

How to Stop the Execution?

The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.

Syntax

window.clearInterval(intervalVariable)
The window.clearInterval() method can be written without the window prefix.
To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar=setInterval("javascript function",milliseconds);
Then you will be able to stop the execution by calling the clearInterval() method.
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction()
{
clearInterval(myVar);
}
</script>

The setTimeout() Method

Syntax

window.setTimeout("javascript function",milliseconds);
The window.setTimeout() method can be written without the window prefix.
The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
The first parameter of setTimeout() should be a function.
The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

Example

Wait 3 seconds, then alert "Hello":
<body>
<p>Click the button to wait 3 seconds, then alert "Hello".</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
setTimeout(function(){alert("Hello")},3000);
}
</script>
</body>

No comments:

Post a Comment