Javascript:
- Is worlds most popular programming language
- It is language for
HTML, for web, for servers, PCS, laptops, tablets, phones and more.
Javascript how to:
- Javascripts in HTML must be inserted between <script> and </script> tags.
- <script> tag lines between the <script> and
</script> contain the javascript: <script>
alert("My First JavaScript");
</script>
Javascript in body:
<!DOCTYPE html>
<html>
<body>
..
<script>
document.write("<h1>This is a
heading</h1>");
document.write("<p>This is a
paragraph</p>");
</script>
..
</body>
</html>
Javascript function in head
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My
First JavaScript Function";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button"
onclick="myFunction()">Try it</button>
</body>
</html>
Javascript function in <body>
<!DOCTYPE html>
<html>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button"
onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="My
First JavaScript Function";
}
</script>
</body>
</html>
External javascripts
<!DOCTYPE html>
<html>
<body>
<script src="myScript.js"></script>
</body>
</html>
Javascript is usually used to manipulate HTML elements
Manipulating HTML
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph</p>
<script>
document.getElementById("demo").innerHTML="My
First JavaScript";
</script>
</body>
</html>
Writing to document output
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<script>
document.write("<p>My First
JavaScript</p>");
</script>
</body>
</html>
Warning:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph.</p>
<button onclick="myFunction()">Try
it</button>
<script>
function myFunction()
{
document.write("Oops! The document disappeared!");
}
</script>
</body>
</html>
Javascript statements
- commands to browser
- tells browser what to do
- tells the browser to write Hello Dolly inside the HTML
element with id=demo
document.getElementById("demo").innerHTML="Hello
Dolly";
Javascript code blocks:
- Javascript statements can be grouped together in blocks
- purpose of block is to make sequence of statements execute
together
- good example of statements grouped together in blocks, are
Javascript functions
function myFunction()
{
document.getElementById("demo").innerHTML="Hello
Dolly";
document.getElementById("myDIV").innerHTML="How
are you?";
}
Breakup the code line:
document.write("Hello \
World!");
Javascript comments:
- make code more readable
// 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.";
Javascript multiline comments:
/*
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.";
Use comments at the end of the line
var x=5; // declare
x and assign 5 to it
var y=x+2; // declare
y and assign x+2 to it
Javascript datatypes:
var pi=3.14;
var person="John Doe";
var answer='Yes I am!';
One statement, many variables
var lastname="Doe", age=30,
job="carpenter";
Javascript Data types:
- Javascript has dynamic types
var x;
// Now x is undefined
var x = 5;
// Now x is a Number
var x = "John"; // Now x is a String
Javascript strings:
var carname="Volvo XC60";
var carname='Volvo XC60';
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
Javascript numbers
var x1=34.00; //
Written with decimals
var x2=34; //
Written without decimals
Javascript
booleans:
var x=true;
var y=false;
Javascript Arrays:
var cars=new Array();
cars[0]="Saab";
cars[1]="Volvo";
cars[2]="BMW";
var cars=new
Array("Saab","Volvo","BMW");
Javascript objects:
var person={firstname:"John",
lastname:"Doe", id:5566};
var person={
firstname : "John",
lastname :
"Doe",
id : 5566
};
Javascript objects:
- Strings, Functions, Arrays, Dates
Objects are just data with properties and method
Properties are values associated with the objects
Methods are actions that objects can perform
Properties of car: name, model, weight, color etc.
Methods of car: start(), drive(), brake() etc.
Objects in Javascript:
var txt = new String("Hello World");
Creating Javascript
objects:
person=new Object();
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
Accessing object
properties:
var message="Hello World!";
var message="Hello World!";
var x=message.length;
Accessing object
methods:
var message="Hello world!";
var message="Hello world!";
var x=message.toUpperCase();
Javascript functions:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()">Try
it</button>
</body>
</html>
Calling function with arguments
<button onclick="myFunction('Harry
Potter','Wizard')">Try it</button>
<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " +
job);
}
</script>
Functions with a return value
function myFunction()
{
var x=5;
return x;
}
Operators:
+ operator used on strings
+ operator used on strings
txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;
txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;
Logical operator:
voteable=(age<18)?"Too young":"Old
enough";
Conditional statements:
if (time<20)
{
x="Good
day";
}
if (time<20)
{
x="Good
day";
}
else
{
x="Good evening";
}
if (time<10)
{
x="Good
morning";
}
else if (time<20)
{
x="Good
day";
}
else
{
x="Good
evening";
}
var day=new Date().getDay();
switch (day)
{
case 0:
x="Today is
Sunday";
break;
case 1:
x="Today is
Monday";
break;
case 2:
x="Today is
Tuesday";
break;
case 3:
x="Today is
Wednesday";
break;
case 4:
x="Today is
Thursday";
break;
case 5:
x="Today is
Friday";
break;
case 6:
x="Today is
Saturday";
break;
}
var day=new Date().getDay();
switch (day)
{
case 6:
x="Today is
Saturday";
break;
case 0:
x="Today is
Sunday";
break;
default:
x="Looking
forward to the Weekend";
}
Javascript loops:
Different kinds of loops:
for- loops through block of code
for/in- loops through properties of an object
while- loops through block of code while specific condition
is true
do/while- loops through block of code while specified
condition is true
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
is same as:
for (var i=0;i<cars.length;i++)
{
document.write(cars[i] + "<br>");
}
var i=2,len=cars.length;
for (; i<len; i++)
{
document.write(cars[i] + "<br>");
}
var i=0,len=cars.length;
for (; i<len; )
{
document.write(cars[i] + "<br>");
i++;
}
var txt="";
var
person={fname:"John",lname:"Doe",age:25};
for (var x in person)
{
txt=txt + person[x];
}
While loop:
while (i<5)
{
x=x + "The
number is " + i + "<br>";
i++;
}
do
{
x=x + "The
number is " + i + "<br>";
i++;
}
while (i<5);
cars=["BMW","Volvo","Saab","Ford"];
var i=0;
for (;cars[i];)
{
document.write(cars[i] + "<br>");
i++;
}
cars=["BMW","Volvo","Saab","Ford"];
var i=0;
while (cars[i])
{
document.write(cars[i] + "<br>");
i++;
}
Javascript break statement
for (i=0;i<10;i++)
{
if (i==3)
{
break;
}
x=x + "The
number is " + i + "<br>";
}
for (i=0;i<10;i++)
{
if (i==3) break;
x=x + "The
number is " + i + "<br>";
}
Continue statement:
for (i=0;i<=10;i++)
{
if (i==3) continue;
x=x + "The
number is " + i + "<br>";
}
Javascript labels:
cars=["BMW","Volvo","Saab","Ford"];
list:
{
document.write(cars[0] + "<br>");
document.write(cars[1] + "<br>");
document.write(cars[2] + "<br>");
break list;
document.write(cars[3] + "<br>");
document.write(cars[4] + "<br>");
document.write(cars[5] + "<br>");
}
Error handling:
<!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+="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>
Throw: allows you to create custom error
<script>
function myFunction()
{
var y=document.getElementById("mess");
y.innerHTML="";
try
{
var
x=document.getElementById("demo").value;
if(x=="") throw
"empty";
if(isNaN(x)) throw
"not a number";
if(x>10) throw "too high";
if(x<5) throw "too low";
}
catch(err)
{
y.innerHTML="Error: " + err + ".";
}
}
</script>
<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button"
onclick="myFunction()">Test Input</button>
<p id="mess"></p>
Javascript form validation
- form data checked by javascript could be:
- has the user left required fields empty?
- has user entered valid email address?
- has the user entered valid date?
- has user entered text in numeric field?
Required fields:
function validateForm()
{
var
x=document.forms["myForm"]["fname"].value;
if (x==null || x=="")
{
alert("First
name must be filled out");
return false;
}
}
<form name="myForm"
action="demo_form.asp" onsubmit="return validateForm()"
method="post">
First name: <input type="text"
name="fname">
<input type="submit"
value="Submit">
</form>
Email validation:
function validateForm()
{
var
x=document.forms["myForm"]["email"].value;
var atpos=x.indexOf("@");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 ||
dotpos+2>=x.length)
{
alert("Not a
valid e-mail address");
return false;
}
}
<form name="myForm"
action="demo_form.asp" onsubmit="return validateForm();" method="post">
Email: <input type="text"
name="email">
<input type="submit"
value="Submit">
</form>
Javascript objects:
Accessing object properties:
objectName.propertyName
var message="Hello World!";
var x=message.length;
Accessing object methods:
objectName.methodName()
var message="Hello world!";
var x=message.toUpperCase();
Creating an direct
instance:
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Using a object constructor:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
Creating direct
instance
person=new Object();
person.firstname="John";
person.lastname="Doe";
person.age=50;
person.eyecolor="blue";
person={firstname:"John",lastname:"Doe",age:50,eyecolor:"blue"};
Using object constructor:
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
Adding methods to Javascript objects
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;
}
}
For..in statement
var
person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
txt=txt + person[x];
}
Javascript Number object
var pi=3.14; // A
number written with decimals
var x=34; // A
number written without decimals
var myNumber=128;
myNumber.toString(16);
// returns 80
myNumber.toString(8);
// returns 200
myNumber.toString(2);
// returns 10000000
Infinity
myNumber=2;
while (myNumber!=Infinity)
{
myNumber=myNumber*myNumber; // Calculate until Infinity
}
NaN - Not a number
var x = 1000 / "Apple";
isNaN(x); // returns true
var y = 100 / "1000";
isNaN(y); // returns false
var x = 123;
var y = new Number(123);
typeof(x) // returns Number
typeof(y) // returns Object
var x = 123;
var y = new Number(123);
(x === y) // is false because x is a number and y is an
object.
Javascript String Object:
- stores series of characters like John Doe
var carname="Volvo XC60";
var carname='Volvo XC60';
var answer="It's alright";
var answer="He is called 'Johnny'";
var answer='He is called "Johnny"';
String length:
var txt="Hello World!";
document.write(txt.length);
var txt="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.write(txt.length);
Finding a string in a string
var str="Hello world, welcome to the universe.";
var n=str.indexOf("welcome");
Matching content:
var str="Hello world!";
document.write(str.match("world") +
"<br>");
document.write(str.match("World") +
"<br>");
document.write(str.match("world!"));
Replacing content:
str="Please visit Microsoft!"
var
n=str.replace("Microsoft","W3Schools");
Uppercase and lowecase:
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 string into array
txt="a,b,c,d,e"
// String
txt.split(",");
// Split on commas
txt.split(" ");
// Split on spaces
txt.split("|");
// Split on pipe
Strings can be string or objects
var x = "John";
var y = new String("John");
typeof(x) // returns String
typeof(y) // returns Object
var x = "John";
var y = new String("John");
(x === y) // is false because x is a string and y is an
object.
Create a date object
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:
var myDate=new Date();
myDate.setFullYear(2010,0,14);
var myDate=new Date();
myDate.setDate(myDate.getDate()+5);
Compare two dates
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");
}
Array: special variable that can hold more than one value at
a time
var myCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
var myCars=new
Array("Saab","Volvo","BMW");
Access an array:
var name=myCars[0];
Different objects in one array:
myArray[0]=Date.now;
myArray[1]=myFunction;
myArray[2]=myCars;
Array Methods and Properties:
var x=myCars.length // the number of elements in myCars
var y=myCars.indexOf("Volvo") // the index position of "Volvo"
Create boolean object
var myBoolean=new Boolean();
Math object:
var x=Math.PI;
var y=Math.sqrt(16);
document.write(Math.round(4.7));
document.write(Math.random());
document.write(Math.floor(Math.random()*11));
RegExp:
- object that describes pattern of characters
- simple pattern can be one single character
var patt=new RegExp(pattern,modifiers);
or more simply:
var patt=/pattern/modifiers;
i: perform case insensitive matching
var str="Visit W3Schools";
var patt1=/w3schools/i;
g: global search for is
var str="Is this all there is?";
var patt1=/is/g;
Is this all there is?
gi: global, case insensitive search
var str="Is this all there is?";
var patt1=/is/gi;
Is this all there is?
test(): searches string for specified value
and returns a true or false depending on result
var patt1=new RegExp("e");
document.write(patt1.test("The best things in life are
free"));
exec() method searches string for specified value and return text of found value. If no match is found,
then it returns null.
var patt1=new RegExp("e");
document.write(patt1.exec("The best things in life are
free"));
Finding HTML elements:
- document.getElementById(): finding element by element id
- document.getElementsByTagName(): finding element by tag
name
- document.getElementsByClassName(): Finding elements by
class name
- document.forms[]: finding elements by HTML element objects
Changing HTML elements:
- document.write(text): writing into HTML output stream
- document.getElementById(id).innerHTML: Changing inner HTML
of an element
- document.getElementById(id).attribute=:changing attribute
of the element
- document.getEelementById(id).style.attribute=: changing
style of an HTML element
Adding and deleting element:
- document.createElement(): create an HTML element
- document.removeChild(): remote an HTML element
- document.appendChild(): add an HTML element
- document.replaceChild(): replace an HTML element
Adding event handlers
- document.getElementById(id).onclick = function(){code}:
Adding event handler code to an onclick event
Finding HTML elemennts by ID:
var x=document.getElementById("intro");
Finding HTML elements by tagname:
var x=document.getElementById("main");
var y=x.getElementsByTagName("p");
Finding HTML elements by classname:
document.getElementsByClassName("intro");
Changing HTML content:
document.getElementById(id).innerHTML=new HTML
<html>
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New
text!";
</script>
</body>
</html>
Changing value of an attribute:
document.getElementById(id).attribute=new value
<!DOCTYPE html>
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
Changing HTML style:
document.getElementById(id).style.property=new style
<html>
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
<p>The paragraph above was changed by a
script.</p>
</body>
</html>
Using events:
<!DOCTYPE html>
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click Me!</button>
</body>
</html>
Reacting to events:
Example of HTML events:
- when user clicks the mouse
- when web page has loaded
- when image has been loaded
- when mouse moves over an element
- when input field is changed
- when HTML form is submitted
- when user strokes a key
<!DOCTYPE html>
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click
on this text!</h1>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this
text!</h1>
</body>
</html>
onload and onunload events: triggered when user enters or
leaves a page.
<body onload="checkCookies()">
onchange Event
<input type="text" id="fname"
onchange="upperCase()">
onmouseover and onmouseout Events
onmousedown, onmouseup and onclick events
Creating new HTML elements(Nodes):
<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>
Create new HTML elements - insertBefore()
<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");
var child=document.getElementById("p1");
element.insertBefore(para,child);
</script>
Removing existing HTML elements
<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>
Replacing HTML elements:
<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 parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.replaceChild(para,child);
</script>
Javascript Window Screen:
- screen.availwidth: available screen width
- screen.availheight: available screen height
<script>
document.write("Available Width: " +
screen.availWidth);
</script>
<script>
document.write("Available Height: " +
screen.availHeight);
</script>
Javascript window location:
- get current page address (URL) and redirect browser to new page
Window location href:
Return entire URL of the current page.
<script>
document.write(location.href);
</script>
Window location pathname
<script>
document.write(location.pathname);
</script>
Window location assign:loads a new document
<html>
<head>
<script>
function newDoc()
{
window.location.assign("http://www.w3schools.com")
}
</script>
</head>
<body>
<input type="button" value="Load new
document" onclick="newDoc()">
</body>
</html>
Javascript Window History
Window History back:
<html>
<head>
<script>
function goBack()
{
window.history.back()
}
</script>
</head>
<body>
<input type="button" value="Back"
onclick="goBack()">
</body>
</html>
Window history forward:
<html>
<head>
<script>
function goForward()
{
window.history.forward()
}
</script>
</head>
<body>
<input type="button" value="Forward"
onclick="goForward()">
</body>
</html>
Window navigator:
<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>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>
Javascript popup boxes:
window.alert("sometext");
alert("I am an alert box!");
window.confirm("sometext");
var r=confirm("Press a button");
if (r==true)
{
x="You pressed
OK!";
}
else
{
x="You pressed
Cancel!";
}
window.prompt("sometext","defaultText");
var person=prompt("Please enter your
name","Harry Potter");
if (person!=null)
{
x="Hello "
+ person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
Line breaks:
alert("Hello\nHow are you?");
Javascript Timing Events:
setInterval() method:
window.setInterval("javascript
function",milliseconds);
setInterval(function(){alert("Hello")},3000);
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
How to stop execution?
window.clearInterval(intervalVariable)
myVar=setInterval("javascript
function",milliseconds);
<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>
setTimeOut method
window.setTimeout("javascript
function",milliseconds);
setTimeout(function(){alert("Hello")},3000);
How to stop execution?
window.clearTimeout(timeoutVariable)
myVar=setTimeout("javascript
function",milliseconds);
var myVar;
function myFunction()
{
myVar=setTimeout(function(){alert("Hello")},3000);
}
function myStopFunction()
{
clearTimeout(myVar);
}
Cookies:
let you store user information in web pages.
Create cookie with javascript:
document.cookie="username=John Doe";
document.cookie="username=John Doe; expires=Thu, 18 Dec
2013 12:00:00 GMT";
document.cookie="username=John Doe; expires=Thu, 18 Dec
2013 12:00:00 GMT; path=/";
Read a cookie with Javascript:
var x = document.cookie;
Change a cookie with Javascript:
document.cookie="username=John Smith; expires=Thu, 18
Dec 2013 12:00:00 GMT; path=/";
Delete a cookie with Javascript
document.cookie = "username=; expires=Thu, 01 Jan 1970
00:00:00 GMT";
Function to set a cookie:
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 to get a cookie:
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 to check a cookie:
function checkCookie()
{
var username=getCookie("username");
if (username!="")
{
alert("Welcome
again " + username);
}
else
{
username =
prompt("Please enter your name:","");
if
(username!="" && username!=null)
{
setCookie("username",username,365);
}
}
}
<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,365);
}
}
}
<body onload="checkCookie()">
</body>
</html>
Javascript libraries:
Advanced Javascript programming can often be very difficult and time consuming to work with. To deal with these difficulties, lot of Javascript libraries have been developed.
These are at time referred as Javascript frameworks
Most popular Javascript frameworks:
- jQuery
- Prototype
- Mootools
- YUI
- Ext JS:
- Dojo
No comments:
Post a Comment