Thursday, March 6, 2014

Javascript continued

CDN: Content Delivery Networks

It is a network of servers containing shared code libraries.

Google provides free CDN for number of Javascript libraries:
- jQuery
- Prototypes
- MooTools
- Dojo
- Yahoo! YUI

Including jQuery

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
</head>
<body>
</body>
</html>

The JavaScript Way:

function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello jQuery";
}
onload=myFunction;

The jQuery Way:

function myFunction()
{
$("#h01").html("Hello jQuery");
}
$(document).ready(myFunction);

Last line of the code passes HTML DOM document object to jQuery: $(document).
jQuery function returns a new jQuery object, where ready() is method

Testing jQuery:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
function myFunction()
{
$("#h01").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
function myFunction()
{
$("#h01").attr("style","color:red").html("Hello jQuery")
}
$(document).ready(myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>

Javascript - Prototype

Including prototype:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js">
</script>
</head>
<body>
</body>
</html>

The JavaScript Way:

function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello Prototype";
}
onload=myFunction;

The Prototype Way:

function myFunction()
{
$("h01").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);

Testing prototype:

<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/
prototype/1.7.1.0/prototype.js">
</script>
<script>
function myFunction()
{
$("h01").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);
</script>
</head>
<body>
<h1 id="h01"></h1>
</body>
</html>

Write to document using javascript

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<script>
document.write("<p>My First JavaScript</p>");
</script>

</body>
</html>

Change HTML elements with Javascript

<!DOCTYPE html>
<html>
<body>

<h1>My First Web Page</h1>

<p id="demo">My First Paragraph.</p>

<script>
document.getElementById("demo").innerHTML="My JavaScript";
</script>

</body>
</html>


External Javascript

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph.</p>

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

<p><strong>Note:</strong> myFunction is stored in an external file called "myScript.js".</p>

<script src="myScript.js"></script>

</body>
</html>

Java script statements:

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="demo">A Paragraph.</p>

<div id="myDIV">A DIV.</div>

<script>
document.getElementById("demo").innerHTML="Hello Dolly";
document.getElementById("myDIV").innerHTML="How are you?";
</script>

</body>
</html>

Javascript blocks:

<!DOCTYPE html>
<html>
<body>

<h1>My Web Page</h1>

<p id="myPar">I am a paragraph.</p>
<div id="myDiv">I am a div.</div>

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

<script>
function myFunction()
{
document.getElementById("myPar").innerHTML="Hello Dolly";
document.getElementById("myDiv").innerHTML="How are you?";
}
</script>

<p>When you click on "Try it", the two elements will change.</p>

</body>
</html>

Single line comments:

<!DOCTYPE html>
<html>
<body>

<h1 id="myH1"></h1>

<p id="myP"></p>

<script>
// Write to a heading:
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
// Write to a paragraph:
document.getElementById("myP").innerHTML="This is my first paragraph.";
</script>

<p><strong>Note:</strong> The comments are not executed.</p>

</body>
</html>

Multi line comments

<!DOCTYPE html>
<html>
<body>

<h1 id="myH1"></h1>

<p id="myP"></p>

<script>
/*
The code below will write to a heading and to a paragraph,
and will represent the start of my homepage:
*/
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
</script>

<p><strong>Note:</strong> The comment-block is not executed.</p>

</body>
</html>

Single line comment to prevent execution

<!DOCTYPE html>
<html>
<body>

<h1 id="myH1"></h1>

<p id="myP"></p>

<script>
//document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
</script>

<p><strong>Note:</strong> The comment is not executed.</p>

</body>
</html>

Multiline comments without execution

<!DOCTYPE html>
<html>
<body>

<h1 id="myH1"></h1>

<p id="myP"></p>

<script>
/*
document.getElementById("myH1").innerHTML="Welcome to my Homepage";
document.getElementById("myP").innerHTML="This is my first paragraph.";
*/
</script>

<p><strong>Note:</strong> The comment-block is not executed.</p>

</body>
</html>

Declare variable, assign value to it and display it

<!DOCTYPE html>
<html>
<body>

<script>
var firstname;
firstname="Hege";
document.write(firstname);
document.write("<br>");
firstname="Tove";
document.write(firstname);
</script>

<p>The script above declares a variable,
assigns a value to it, displays the value, changes the value,
and displays the value again.</p>

</body>
</html>

If statement:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get a "Good day" greeting if the time is less than 20:00.</p>

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

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

<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<20)
  {
  x="Good day";
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>


If...else statement

<!DOCTYPE html>
<html>
<body>

<p>Click the button to get a time-based greeting.</p>

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

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

<script>
function myFunction()
{
var x="";
var time=new Date().getHours();
if (time<20)
  {
  x="Good day";
  }
else
  {
  x="Good evening";
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Random link

<!DOCTYPE html>
<html>
<body>

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

<script>
var r=Math.random();
var x=document.getElementById("demo")
if (r>0.5)
{
x.innerHTML="<a href='http://w3schools.com'>Visit W3Schools</a>";
}
else
{
x.innerHTML="<a href='http://wwf.org'>Visit WWF</a>";
}
</script>

</body>
</html>

Alert box:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to display an alert box.</p>

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

<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>

</body>
</html>

Alert box with line breaks

<!DOCTYPE html>
<html>
<body>

<p>Click the button to demonstrate line-breaks in a popup box.</p>

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

<script>
function myFunction()
{
alert("Hello\nHow are you?");
}
</script>

</body>
</html>

Confirm box:

<!DOCTYPE html>
<html>
<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>
</html>

Prompt box:

<!DOCTYPE html>
<html>
<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>
</html>

Call a function

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>

<body>

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

<p>By clicking the button above, a function will be called. The function will alert a message.</p>

</body>
</html>


<!DOCTYPE html>
<html>
<body>

<p>Click the button to call a function with arguments</p>

<button onclick="myFunction('Harry Potter','Wizard')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

</body>
</html>

Function that returns a value

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
return ("Hello world!");
}
</script>
</head>
<body>

<script>
document.write(myFunction())
</script>

</body>
</html>

Function with arguments that returns a value

<!DOCTYPE html>
<html>
<body>

<p>This example calls a function which performs a calculation, and returns the result:</p>

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

<script>
function myFunction(a,b)
{
return a*b;
}

document.getElementById("demo").innerHTML=myFunction(4,3);
</script>


For loop:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i;
for (i=0;i<5;i++)
  {
  x=x + "The number is " + i + "<br>";
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Looping through HTML headers

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop from 1 to 6, to make HTML headings.</p>
<button onclick="myFunction()">Try it</button>
<div id="demo"></div>

<script>
function myFunction()
{
var x="",i;
for (i=1; i<=6; i++)
{
x=x + "<h" + i + ">Heading " + i + "</h" + i + ">";
}
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

While loop:

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop through a block of as long as <em>i</em> is less than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
while (i<5)
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>


Do while loop

<!DOCTYPE html>
<html>
<body>

<p>Click the button to loop through a block of as long as <em>i</em> is less than 5.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
do
  {
  x=x + "The number is " + i + "<br>";
  i++;
  }
while (i<5) 
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>


Break a loop

<!DOCTYPE html>
<html>
<body>

<p>Click the button to do a loop with a break.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

<script>
function myFunction()
{
var x="",i=0;
for (i=0;i<10;i++)
  {
  if (i==3)
    {
    break;
    }
  x=x + "The number is " + i + "<br>";
  }
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>

Use a for...in statement to loop through the elements 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 txt="";
var person={fname:"John",lname:"Doe",age:25};

for (var x in person)
{
txt=txt + person[x];
}

document.getElementById("demo").innerHTML=txt;
}
</script>
</body>
</html>


Onclick event

<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{
document.getElementById("demo").innerHTML=Date();
}
</script>
</head>
<body>

<h1>My First JavaScript</h1>
<p id="demo">This is a paragraph.</p>

<button type="button" onclick="displayDate()">Display Date</button>

</body>
</html>


Onmouseover event

<!DOCTYPE html>
<html>
<head>
<script>
function writeText(txt)
{
document.getElementById("desc").innerHTML=txt;
}
</script>
</head>

<body>
<img src ="planets.gif" width ="145" height ="126" alt="Planets" usemap="#planetmap" />

<map name="planetmap">
<area shape ="rect" coords ="0,0,82,126"
onmouseover="writeText('The Sun and the gas giant planets like Jupiter are by far the largest objects in our Solar System.')"
href ="sun.htm" target ="_blank" alt="Sun" />

<area shape ="circle" coords ="90,58,3"
onmouseover="writeText('The planet Mercury is very difficult to study from the Earth because it is always so close to the Sun.')"
href ="mercur.htm" target ="_blank" alt="Mercury" />

<area shape ="circle" coords ="124,58,8"
onmouseover="writeText('Until the 1960s, Venus was often considered a twin sister to the Earth because Venus is the nearest planet to us, and because the two planets seem to share many characteristics.')"
href ="venus.htm" target ="_blank" alt="Venus" />
</map>

<p id="desc">Mouse over the sun and the planets and see the different descriptions.</p>

</body>
</html>


Try catch statement

<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
  {
  addAlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Error description: " + err.message + "\n\n";
  txt+="Click OK to continue.\n\n";
  alert(txt);
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>


Try catch statement with confirm box:

<!DOCTYPE html>
<html>
<head>
<script>
var txt="";
function message()
{
try
  {
  adddlert("Welcome guest!");
  }
catch(err)
  {
  txt="There was an error on this page.\n\n";
  txt+="Click OK to continue viewing this page,\n";
  txt+="or Cancel to return to the home page.\n\n";
  if(!confirm(txt))
    {
    document.location.href="http://www.w3schools.com/";
    }
  }
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>


OnError Event:

<!DOCTYPE html>
<html>
<head>
<script>
onerror=handleErr;
var txt="";

function handleErr(msg,url,l)
{
txt="There was an error on this page.\n\n";
txt+="Error: " + msg + "\n";
txt+="URL: " + url + "\n";
txt+="Line: " + l + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
return true;
}

function message()
{
addAlert("Welcome guest!");
}
</script>
</head>

<body>
<input type="button" value="View message" onclick="message()" />
</body>

</html>

Create a welcome cookie

<!DOCTYPE html>
<html>
<head><script>

function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
}

function checkCookie()
{
var user=getCookie("username");
if (user!="")
  {
  alert("Welcome again " + user);
  }
else
  {
  user = prompt("Please enter your name:","");
  if (user!="" && user!=null)
    {
    setCookie("username",user,30);
    }
  }
}

</script></head>

<body onload="checkCookie()"></body>
</html>

Simple timing

<!DOCTYPE html>
<html>
<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>
</html>

Timing in infinite loop with stop button

<!DOCTYPE html>
<html>
<head>
<script>
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout(function(){timedCount()},1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Clock created with timing event

<!DOCTYPE html>
<html>
<head>
<script>
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout(function(){timedCount()},1000);
}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Create an direct instance of the object

<!DOCTYPE html>
<html>
<body>

<script>
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"}

document.write(person.firstname + " is " + person.age + " years old.");
</script>

</body>
</html>

Create an object constructor

<!DOCTYPE html>
<html>
<body>

<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}

myFather=new person("John","Doe",50,"blue");

document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>

</body>

</html>

No comments:

Post a Comment