Você está na página 1de 36

Javascript:-

Check Cookie is enabled or not:-


if (navigator.cookieEnabled) {
alert("This browser supports cookies");
}
else {
alert("This browser does not support cookies");
}

Link click alert:-

Page1:-
<body>
<h2 align="center">
<a href="index.html" id="redirect">Welcome to our site... c'mon in!</a>
</h2>
</body>

Page2:-
window.onload = initAll;

function initAll() {
document.getElementById("redirect").onclick = clickHandler;
}

function clickHandler() {
alert("Ow, that hurt!");
return false;
}

Page redirecting when clicked:-

Page1:-
<html>
<head>
<title>Welcome to our site</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h2 align="center">
Hey, check out <a href="http://www.pixel.mu/" id="redirect">my cat's Web site</a>.
</h2>
</body>
</html>
Page2:-

window.onload = initAll;

function initAll() {
document.getElementById("redirect").onclick = clickHandler;
}

function clickHandler() {
window.location = "jswelcome.html";
return false;
}
Redirecting with a prompt:-

Page 1:-

<html>
<head>
<title>Welcome to our site</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h2 align="center">
Hey, check out <a href="http://www.pixel.mu/" id="redirect">my cat's Web site</a>.
</h2>
</body>
</html>

Script File:-
window.onload = initAll;

function initAll() {
document.getElementById("redirect").onclick = clickHandler;
}

function clickHandler() {
if (this.toString().indexOf("dori") < 0) {
alert("We are not responsible for the content of pages outside our site");
}
}

Switch-Case:-
window.onload = initAll;

function initAll() {
switch(navigator.platform) {
case "Win32":
alert("You're running Windows");
break;
case "MacPPC":
alert("You have a PowerPC-based Mac");
break;
case "MacIntel":
case "X11":
alert("You have an Intel-based Mac");
break;
default:
alert("You have " + navigator.platform);
}
}
Square Root Calculator:-

<html>
<head>
<title>Square Root Calculator</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<noscript>
<h2>This page requires JavaScript.</h2>
</noscript>
</body>
</html>

window.onload = initAll;

function initAll() {
var ans = prompt("Enter a number","");
try {
if (!ans || isNaN(ans) || ans<0) {
throw new Error("Not a valid number");
}
alert("The square root of " + ans + " is " + Math.sqrt(ans));
}
catch (errMsg) {
alert(errMsg.message);
}
}
IMAGE ROLL OVER:-

<html>
<head>
<title>A Simple Rollover</title>
<link rel="stylesheet" rev="stylesheet" href="styles.css" />
</head>
<body>
<a href="next.html" onmouseover="document.arrow.src='images/arrow_on.gif'"
onmouseout="document.arrow.src='images/arrow_off.gif'"><img src="images/arrow_off.gif"
width="147" height="82" name="arrow" alt="arrow" /></a>
</body>
</html>
MORE EFFECTIVE ROLLOVER:-

<html>
<head>
<title>A More Effective Rollover</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" rev="stylesheet" href="styles.css" />
</head>
<body>
<a href="next1.html"><img src="images/button1_off.gif" width="113" height="33"
alt="button1" id="button1" /></a>&nbsp;&nbsp;
<a href="next2.html"><img src="images/button2_off.gif" width="113" height="33"
alt="button2" id="button2" /></a>
</body>
</html>

window.onload = rolloverInit;

function rolloverInit() {
for (var i=0; i<document.images.length; i++) {
if (document.images[i].parentNode.tagName == "A") {
setupRollover(document.images[i]);
}
}
}

function setupRollover(thisImage) {
thisImage.outImage = new Image();
thisImage.outImage.src = thisImage.src;
thisImage.onmouseout = rollOut;

thisImage.overImage = new Image();


thisImage.overImage.src = "images/" + thisImage.id + "_on.gif";
thisImage.onmouseover = rollOver;
}

function rollOut() {
this.src = this.outImage.src;
}

function rollOver() {
this.src = this.overImage.src;
}
LINK ROLL OVER:-

<html>
<head>
<title>Link Rollover</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" rev="stylesheet" href="styles.css" />
</head>
<body>
<h1><a href="next.html" id="arrow">Next page</a></h1>
<img src="images/arrow_off.gif" width="147" height="82" id="arrowImg" alt="arrow" />
</body>
</html>

window.onload = rolloverInit;

function rolloverInit() {
for (var i=0; i<document.links.length; i++) {
var linkObj = document.links[i];
if (linkObj.id) {
var imgObj = document.getElementById(linkObj.id +
"Img");
if (imgObj) {
setupRollover(linkObj,imgObj);
}
}
}
}

function setupRollover(thisLink,thisImage) {
thisLink.imgToChange = thisImage;
thisLink.onmouseout = rollOut;
thisLink.onmouseover = rollOver;

thisLink.outImage = new Image();


thisLink.outImage.src = thisImage.src;

thisLink.overImage = new Image();


thisLink.overImage.src = "images/" + thisLink.id + "_on.gif";
}

function rollOut() {
this.imgToChange.src = this.outImage.src;
}

function rollOver() {
this.imgToChange.src = this.overImage.src;
}

IMAGE SLIDE SHOW:-

<html>
<head>
<title>Image Slideshow</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" rev="stylesheet" href="styles.css" />
</head>
<body>
<div align="center">
<h1>US Missions to Mars</h1>
<img src="images/pathfinder.gif" id="myPicture" width="201" height="155"
alt="Slideshow" />
<h2><a href="previous.html" id="prevLink">&laquo; Previous</a>&nbsp;&nbsp;<a
href="next.html" id="nextLink">Next &raquo;</a></h2>
</div>
</body>
</html>

window.onload = initLinks;

var myPix = new Array("images/pathfinder.gif","images/surveyor.gif","images/surveyor98.gif");


var thisPic = 0;

function initLinks() {
document.getElementById("prevLink").onclick = processPrevious;
document.getElementById("nextLink").onclick = processNext;
}

function processPrevious() {
if (thisPic == 0) {
thisPic = myPix.length;
}
thisPic--;
document.getElementById("myPicture").src = myPix[thisPic];
return false;
}

function processNext() {
thisPic++;
if (thisPic == myPix.length) {
thisPic = 0;
}
document.getElementById("myPicture").src = myPix[thisPic];
return false;
}

body {
background-color: white;
}
img {
border-width: 0;
}
RANDOM IMAGE:

<html>
<head>
<title>Random Image</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" rev="stylesheet" href="styles.css" />
</head>
<body>
<img src="images/spacer.gif" width="321" height="480" id="myPicture" alt="some image" />
</body>
</html>

window.onload = choosePic;

var myPix = new


Array("images/teacup00.jpg","images/teacup01.jpg","images/teacup02.jpg","images/teacup03.jpg","im
ages/teacup04.jpg","images/teacup05.jpg","images/teacup06.jpg","images/teacup07.jpg");

function choosePic() {
randomNum = Math.floor((Math.random() * myPix.length));
document.getElementById("myPicture").src = myPix[randomNum];
}

body {
background-color: white;
}
img {
border-width: 0;
}

COMBO BOX :-

<html>
<head>
<title>Select and Go Navigation</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<div align="center">
<form action="gotoLocation.cgi">
<select id="newLocation">
<option selected="selected">Select a destination</option>
<option value="hawaii.html">Hawaii</option>
<option value="alaska.html">Alaska</option>
<option value="california.html">California</option>
<option value="florida.html">Florida</option>
</select>
<noscript>
<input type="submit" value="Go There!" />
</noscript>
</form>
</div>
</body>
</html>

window.onload = initForm;
window.onunload = function() {};

function initForm() {
document.getElementById("newLocation").selectedIndex = 0;
document.getElementById("newLocation").onchange = jumpPage;
}

function jumpPage() {
var newLoc = document.getElementById("newLocation");
var newPage = newLoc.options[newLoc.selectedIndex].value;

if (newPage != "") {
window.location = newPage;
}
}

DYNAMIC LOADING OF COMBOBOXES WITH RESPECT TO ANOTHER COMBOBOX:-

<html>
<head>
<title>Dynamic Menus</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<select id="months">
<option value="">Month</option>
<option value="0">January</option>
<option value="1">February</option>
<option value="2">March</option>
<option value="3">April</option>
<option value="4">May</option>
<option value="5">June</option>
<option value="6">July</option>
<option value="7">August</option>
<option value="8">September</option>
<option value="9">October</option>
<option value="10">November</option>
<option value="11">December</option>
</select>
&nbsp;

<select id="days">
<option>Day</option>
</select>
</form>

</body>
</html>

window.onload = initForm;

function initForm() {
document.getElementById("months").selectedIndex = 0;
document.getElementById("months").onchange = populateDays;
}

function populateDays() {
var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
var monthStr = this.options[this.selectedIndex].value;

if (monthStr != "") {
var theMonth = parseInt(monthStr);

document.getElementById("days").options.length = 0;
for(var i=0; i<monthDays[theMonth]; i++) {
document.getElementById("days").options[i] = new Option(i+1);
}
}
}
Automatic page redirection
Several times you visit a website and you see a message saying that this page has been moved
and after few seconds you are automatically redirected to the new and correct location of the
page. Another variation is to have a slideshow in which a set of pages are being displayed
successively one after one with a duration of few seconds within every page. Several other
scenarios can be implemented, so the actual applications are open to your imagination.

The script itself is as simple as the following:

     1 < H3 >


     2     You will be redirected to the page "s4.htm" after 3 seconds ....
     3 </ H3 >
     4 <! --================================================-- >
     5 < SCRIPT LANGUAGE =JAVASCRIPT> <!--
     6 //----------
     7 function redirectPage()
   
     8     {
     9        location = "s4.htm"
    10     }
    11 //----------
    12     setTimeout("redirectPage()", 3000);
    13  //--> </ SCRIPT >
    14 <! --================================================-- >

The above script display a message to the user that he or she will be redirected within 3 seconds
(line 2). The new page to which the user is to be redirected is indicated in the statement in line 9.
The duration after which the user is redirected is indicated in line 12 in unites of milliseconds.

When this script runs, it displays the following page:

Figure 7

... and after 3 seconds the page "s4.htm" will be automatically displayed.
Invalid Data:-

body {
color: #000;
background-color: #FFF;
}

input.invalid {
background-color: #FF9;
border: 2px red inset;
}

label.invalid {
color: #F00;
font-weight: bold;
}

select {
margin-left: 80px;
}

input {
margin-left: 30px;
}

input+select, input+input {
margin-left: 20px;
}

<html>
<head>
<title>Car Picker</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="script.css" />
</head>
<body>
<h2 align="center">Car Picker</h2>
<form action="#">
<p>
<label for="emailAddr">Enter your email
address:&nbsp;&nbsp;&nbsp;&nbsp; <input id="emailAddr" type="text" size="30"
class="reqd email" />
</label></br />
<label for="emailAddr2">Re-enter your email address:<input
id="emailAddr2" type="text" size="30" class="reqd emailAddr" />
</label>
</p>
<p><label for="color">Colors:
<select id="color" class="reqd">
<option value="" selected="selected">Choose a
color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
</label></p>
<p>Options:
<label for="sunroof"><input type="checkbox" id="sunroof"
value="Yes" />Sunroof (Two door only)</label>
<label for="pWindows"><input type="checkbox" id="pWindows"
value="Yes" />Power Windows</label>
</p>
<p><label for="DoorCt">Doors:&nbsp;&nbsp;
<input type="radio" id="twoDoor" name="DoorCt" value="twoDoor"
class="radio" />Two
<input type="radio" id="fourDoor" name="DoorCt"
value="fourDoor" class="radio" />Four
</label></p>
<p><input type="submit" value="Submit" />&nbsp;<input type="reset"
/></p>
</form>
</body>
</html>

Validity for the following :-

Car Picker

Enter your email address:    

Re-enter your email address:

Choose a color

Colors:

Options: Sunroof (Two door only) Power Windows

Doors:   Two Four

Submit

<html>
<head>
<title>Car Picker</title>
<script type="text/javascript" src="script.js"></script>
<link rel="stylesheet" href="script.css" />
</head>
<body>
<h2 align="center">Car Picker</h2>
<form action="#">
<p>
<label for="emailAddr">Enter your email
address:&nbsp;&nbsp;&nbsp;&nbsp; <input id="emailAddr" type="text" size="30"
class="reqd email" />
</label></br />
<label for="emailAddr2">Re-enter your email address:<input
id="emailAddr2" type="text" size="30" class="reqd emailAddr" />
</label>
</p>
<p><label for="color">Colors:
<select id="color" class="reqd">
<option value="" selected="selected">Choose a
color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
</label></p>
<p>Options:
<label for="sunroof"><input type="checkbox" id="sunroof"
value="Yes" />Sunroof (Two door only)</label>
<label for="pWindows"><input type="checkbox" id="pWindows"
value="Yes" />Power Windows</label>
</p>
<p><label for="DoorCt">Doors:&nbsp;&nbsp;
<input type="radio" id="twoDoor" name="DoorCt" value="twoDoor"
class="radio" />Two
<input type="radio" id="fourDoor" name="DoorCt"
value="fourDoor" class="radio" />Four
</label></p>
<p><input type="submit" value="Submit" />&nbsp;<input type="reset"
/></p>
</form>
</body>
</html>

window.onload = initForms;

function initForms() {
for (var i=0; i< document.forms.length; i++) {
document.forms[i].onsubmit = function() {return validForm();}
}
document.getElementById("sunroof").onclick = doorSet;
}

function validForm() {
var allGood = true;
var allTags = document.getElementsByTagName("*");

for (var i=0; i<allTags.length; i++) {


if (!validTag(allTags[i])) {
allGood = false;
}
}
return allGood;

function validTag(thisTag) {
var outClass = "";
var allClasses = thisTag.className.split(" ");

for (var j=0; j<allClasses.length; j++) {


outClass += validBasedOnClass(allClasses[j]) + " ";
}

thisTag.className = outClass;

if (outClass.indexOf("invalid") > -1) {


invalidLabel(thisTag.parentNode);
thisTag.focus();
if (thisTag.nodeName == "INPUT") {
thisTag.select();
}
return false;
}
return true;

function validBasedOnClass(thisClass) {
var classBack = "";

switch(thisClass) {
case "":
case "invalid":
break;
case "reqd":
if (allGood && thisTag.value == "") {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "radio":
if (allGood && !
radioPicked(thisTag.name)) {
classBack = "invalid ";
}
classBack += thisClass;
break;
case "email":
if (allGood && !
validEmail(thisTag.value)) {
classBack = "invalid ";
}
classBack += thisClass;
break;
default:
if (allGood && !
crossCheck(thisTag,thisClass)) {
classBack = "invalid ";
}
classBack += thisClass;
}
return classBack;
}

function crossCheck(inTag,otherFieldID) {
if (!document.getElementById(otherFieldID)) {
return false;
}
return (inTag.value ==
document.getElementById(otherFieldID).value);
}

function radioPicked(radioName) {
var radioSet = "";

for (var k=0; k<document.forms.length; k++) {


if (!radioSet) {
radioSet = document.forms[k]
[radioName];
}
}
if (!radioSet) return false;
for (k=0; k<radioSet.length; k++) {
if (radioSet[k].checked) {
return true;
}
}
return false;
}

function validEmail(email) {
var invalidChars = " /:,;";

if (email == "") {
return false;
}
for (var k=0; k<invalidChars.length; k++) {
var badChar = invalidChars.charAt(k);
if (email.indexOf(badChar) > -1) {
return false;
}
}
var atPos = email.indexOf("@",1);
if (atPos == -1) {
return false;
}
if (email.indexOf("@",atPos+1) != -1) {
return false;
}
var periodPos = email.indexOf(".",atPos);
if (periodPos == -1) {
return false;
}
if (periodPos+3 > email.length) {
return false;
}
return true;
}

function invalidLabel(parentTag) {
if (parentTag.nodeName == "LABEL") {
parentTag.className += " invalid";
}
}
}
}

function doorSet() {
if (this.checked) {
document.getElementById("twoDoor").checked = true;
}
}

Mouse Movements:-

<html>
<head>
<title>Mouse Movements</title>
<script type="text/javascript" src="script.js">
</script>
<link rel="stylesheet" href="script.css" />
</head>
<body>
<img src="images/circle.gif" alt="left eye" width="24" height="25"
id="lEye" />
<img src="images/circle.gif" alt="right eye" width="24" height="25"
id="rEye" />
<img src="images/lilRed.gif" alt="left eyeball" width="4" height="4"
id="lDot" />
<img src="images/lilRed.gif" alt="right eyeball" width="4" height="4"
id="rDot" />
</body>
</html>

body {
background-color: #FFF;
}

#lEye, #rEye {
position: absolute;
top: 100px;
}

#lDot, #rDot {
position: absolute;
top: 113px;
}
#lEye {
left: 100px;
}

#rEye {
left: 150px;
}

#lDot {
left: 118px;
}

#rDot {
left: 153px;
}

document.onmousemove = moveHandler;

function moveHandler(evt) {
if (!evt) {
evt = window.event;
}
animateEyes(evt.clientX,evt.clientY);
}

function animateEyes(xPos,yPos) {
var rightEye = document.getElementById("rEye");
var leftEye = document.getElementById("lEye");
var rightEyeball = document.getElementById("rDot").style;
var leftEyeball = document.getElementById("lDot").style;

leftEyeball.left = newEyeballPos(xPos,leftEye.offsetLeft);
leftEyeball.top = newEyeballPos(yPos,leftEye.offsetTop);
rightEyeball.left = newEyeballPos(xPos,rightEye.offsetLeft);
rightEyeball.top = newEyeballPos(yPos,rightEye.offsetTop);

function newEyeballPos(currPos,eyePos) {
return Math.min(Math.max(currPos,eyePos+3),eyePos+17) + "px";
}
}

Double-click on an image to see the full-size version


<html>
<head>
<title>Image Popup</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h3>Double-click on an image to see the full-size version</h3>
<img src="images/Img0_thumb.jpg" width="160" height="120" hspace="10"
border="3" alt="Thumbnail 0" id="Img0" />
<img src="images/Img1_thumb.jpg" width="160" height="120" hspace="10"
border="3" alt="Thumbnail 1" id="Img1" />
<img src="images/Img2_thumb.jpg" width="160" height="120" hspace="10"
border="3" alt="Thumbnail 2" id="Img2" />
</body>
</html>
window.onload = initImages;

function initImages() {
for (var i=0; i<document.images.length; i++) {
document.images[i].ondblclick = newWindow;
}
}

function newWindow() {
var imgName = "images/" + this.id + ".jpg";
var imgWindow = window.open(imgName, "imgWin",
"width=320,height=240,scrollbars=no");
}
REQUIRING AN ENTRY:-
<html>
<head>
<title>Requiring an entry</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<h3>
Email address: <input type="text" class="reqd" /><br /><br />
Name (optional): <input type="text" />
</h3>
</form>
</body>
</html>

window.onload = initForm;

function initForm() {
var allTags = document.getElementsByTagName("*");

for (var i=0; i<allTags.length; i++) {


if (allTags[i].className.indexOf("reqd") > -1) {
allTags[i].onblur = fieldCheck;
}
}
}

function fieldCheck() {
if (this.value == "") {
this.style.backgroundColor = "#FFFF99";
this.focus();
}
else {
this.style.backgroundColor = "#FFFFFF";
}
}

FORBIDDING AN ENTRY:-

<html>
<head>
<title>Forbidding an entry</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<h3>
Your message: <textarea rows="5" cols="30">Enter your message
here</textarea><br /><br />
Will be sent to: <input type="text"
value="js6@javascriptworld.com" readonly="readonly" />
</h3>
</form>
</body>
</html>

window.onload = initForm;

function initForm() {
var allTags = document.getElementsByTagName("*");

for (var i=0; i<allTags.length; i++) {


if (allTags[i].readOnly) {
allTags[i].onfocus = skipField;
}
}
}

function skipField() {
this.blur();
}

Use the right and left arrows on your keyboard to view the slideshow

<html>
<head>
<title>Image Slideshow</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h3 align="center">
<img src="images/callisto.jpg" id="myPicture" width="262"
height="262" alt="Slideshow" /><br />
Use the right and left arrows on your keyboard to view the
slideshow
</h3>
</body>
</html>

document.onkeydown = keyHit;
var thisPic = 0;

function keyHit(evt) {
var myPix = new
Array("images/callisto.jpg","images/europa.jpg","images/io.jpg","images/ganyme
de.jpg");
var imgCt = myPix.length-1;
var ltArrow = 37;
var rtArrow = 39;
var thisKey;

if (evt) {
thisKey = evt.which;
}
else {
thisKey = window.event.keyCode;
}

if (thisKey == ltArrow) {
chgSlide(-1);
}
else {
if (thisKey == rtArrow) {
chgSlide(1);
}
}
return false;

function chgSlide(direction) {
thisPic = thisPic + direction;
if (thisPic > imgCt) {
thisPic = 0;
}
if (thisPic < 0) {
thisPic = imgCt;
}
document.getElementById("myPicture").src = myPix[thisPic];
}
}
Handling more than one cookie:-

<html>
<head>
<title>Handling more than one cookie</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h2 id="cookieData">&nbsp;</h2>
</body>
</html>

window.onload = initPage;

function initPage() {
var now = new Date();
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth()+6);

var hitCt = parseInt(cookieVal("pageHit"));


hitCt++;

var lastVisit = cookieVal("pageVisit");


if (lastVisit == 0) {
lastVisit = "";
}

document.cookie = "pageHit=" + hitCt + ";path=/;expires=" +


expireDate.toGMTString();
document.cookie = "pageVisit=" + now + ";path=/;expires=" +
expireDate.toGMTString();

var outMsg = "You have visited this page " + hitCt + " times.";
if (lastVisit != "") {
outMsg += "<br />Your last visit was " + lastVisit;
}
document.getElementById("cookieData").innerHTML = outMsg;
}

function cookieVal(cookieName) {
var thisCookie = document.cookie.split("; ");

for (var i=0; i<thisCookie.length; i++) {


if (cookieName == thisCookie[i].split("=")[0]) {
return thisCookie[i].split("=")[1];
}
}
return 0;
}

SETTING COOKIES

<html>
<head>
<title>Set a cookie based on a form</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<h1>Enter your name: <input type="text" id="nameField" /></h1>
</form>
</body>
</html>
window.onload = nameFieldInit;

function nameFieldInit() {
var userName = "";
if (document.cookie != "") {
userName = document.cookie.split("=")[1];
}

document.getElementById("nameField").value = userName;
document.getElementById("nameField").onblur = setCookie;
}

function setCookie() {
var expireDate = new Date();
expireDate.setMonth(expireDate.getMonth()+6);

var userName = document.getElementById("nameField").value;


document.cookie = "userName=" + userName + ";path=/;expires=" +
expireDate.toGMTString();
}

RETRIEVING COOKIES:-

<html>
<head>
<title>I know your name!</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h1 id="nameField">&nbsp;</h1>
</body>
</html>

window.onload = nameFieldInit;

function nameFieldInit() {
if (document.cookie != "") {
document.getElementById("nameField").innerHTML = "Hello, " +
document.cookie.split("=")[1];
}
}

ADDING NODES:-

<html>
<head>
<title>Adding Nodes</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<input type="submit" value="Add some text to the page" />
</form>
</body>
</html>
window.onload = initAll;

function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
}

function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);

var newGraf = document.createElement("p");


newGraf.appendChild(newText);

var docBody = document.getElementsByTagName("body")[0];


docBody.appendChild(newGraf);

return false;
}

DELETE LAST NODE:-

<html>
<head>
<title>Deleting Nodes</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<input type="submit" value="Add some text to the page" />
</form>
<a id="deleteNode" href="#">Delete last paragraph</a>
</body>
</html>

window.onload = initAll;

function initAll() {
document.getElementsByTagName("form")[0].onsubmit = addNode;
document.getElementById("deleteNode").onclick = delNode;
}

function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);

var newGraf = document.createElement("p");


newGraf.appendChild(newText);

var docBody = document.getElementsByTagName("body")[0];


docBody.appendChild(newGraf);

return false;
}

function delNode() {
var allGrafs = document.getElementsByTagName("p");

if (allGrafs.length > 1) {
var lastGraf = allGrafs.item(allGrafs.length-1);
var docBody = document.getElementsByTagName("body")[0];
var removed = docBody.removeChild(lastGraf);
}
else {
alert("Nothing to remove!");
}

return false;
}

Add node Delete node Insert before node

Submit
Paragraph #:

<html>
<head>
<title>Inserting Nodes</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<p><label><input type="radio" name="nodeAction" />Add
node</label>
<label><input type="radio" name="nodeAction" />Delete
node</label>
<label><input type="radio" name="nodeAction" />Insert before
node</label></p>
Paragraph #: <select id="grafCount"></select>
<input type="submit" value="Submit" />
</form>
<div id="modifiable"> </div>
</body>
</html>

window.onload = initAll;
var nodeChangingArea;

function initAll() {
document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
nodeChangingArea = document.getElementById("modifiable");
}

function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);

var newGraf = document.createElement("p");


newGraf.appendChild(newText);

nodeChangingArea.appendChild(newGraf);
}

function delNode() {
var delChoice = document.getElementById("grafCount").selectedIndex;
var allGrafs = nodeChangingArea.getElementsByTagName("p");
var killGraf = allGrafs.item(delChoice);

nodeChangingArea.removeChild(killGraf);
}

function insertNode() {
var inChoice = document.getElementById("grafCount").selectedIndex;
var inText = document.getElementById("textArea").value;

var newText = document.createTextNode(inText);


var newGraf = document.createElement("p");
newGraf.appendChild(newText);

var allGrafs = nodeChangingArea.getElementsByTagName("p");


var oldGraf = allGrafs.item(inChoice);

nodeChangingArea.insertBefore(newGraf,oldGraf);
}

function nodeChanger() {
var actionType = -1;
var currentPgraphCount =
nodeChangingArea.getElementsByTagName("p").length;
var radioButtonSet = document.getElementsByTagName("form")
[0].nodeAction;

for (var i=0; i<radioButtonSet.length; i++) {


if (radioButtonSet[i].checked) {
actionType = i;
}
}

switch(actionType) {
case 0:
addNode();
break;
case 1:
if (currentPgraphCount > 0) {
delNode();
break;
}
case 2:
if (currentPgraphCount > 0) {
insertNode();
break;
}
default:
alert("No valid action was chosen");
}

document.getElementById("grafCount").options.length = 0;

for (i=0; i<nodeChangingArea.getElementsByTagName("p").length; i++) {


document.getElementById("grafCount").options[i] = new
Option(i+1);
}

return false;
}

Add node Delete node Insert before node Replace node

Submit
Paragraph #:

<html>
<head>
<title>Replacing Nodes</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<form action="#">
<p><textarea id="textArea" rows="5" cols="30"></textarea></p>
<p><label><input type="radio" name="nodeAction" />Add
node</label>
<label><input type="radio" name="nodeAction" />Delete
node</label>
<label><input type="radio" name="nodeAction" />Insert before
node</label>
<label><input type="radio" name="nodeAction" />Replace
node</label></p>
Paragraph #: <select id="grafCount"></select>
<input type="submit" value="Submit" />
</form>
<div id="modifiable"> </div>
</body>
</html>

window.onload = initAll;
var nodeChangingArea;

function initAll() {
document.getElementsByTagName("form")[0].onsubmit = nodeChanger;
nodeChangingArea = document.getElementById("modifiable");
}

function addNode() {
var inText = document.getElementById("textArea").value;
var newText = document.createTextNode(inText);

var newGraf = document.createElement("p");


newGraf.appendChild(newText);

nodeChangingArea.appendChild(newGraf);
}

function delNode() {
var delChoice = document.getElementById("grafCount").selectedIndex;
var allGrafs = nodeChangingArea.getElementsByTagName("p");
var killGraf = allGrafs.item(delChoice);

nodeChangingArea.removeChild(killGraf);
}

function insertNode() {
var inChoice = document.getElementById("grafCount").selectedIndex;
var inText = document.getElementById("textArea").value;

var newText = document.createTextNode(inText);


var newGraf = document.createElement("p");
newGraf.appendChild(newText);

var allGrafs = nodeChangingArea.getElementsByTagName("p");


var oldGraf = allGrafs.item(inChoice);

nodeChangingArea.insertBefore(newGraf,oldGraf);
}

function replaceNode() {
var inChoice = document.getElementById("grafCount").selectedIndex;
var inText = document.getElementById("textArea").value;

var newText = document.createTextNode(inText);


var newGraf = document.createElement("p");
newGraf.appendChild(newText);

var allGrafs = nodeChangingArea.getElementsByTagName("p");


var oldGraf = allGrafs.item(inChoice);

nodeChangingArea.replaceChild(newGraf,oldGraf);
}

function nodeChanger() {
var actionType = -1;
var currentPgraphCount =
nodeChangingArea.getElementsByTagName("p").length;
var radioButtonSet = document.getElementsByTagName("form")
[0].nodeAction;

for (var i=0; i<radioButtonSet.length; i++) {


if (radioButtonSet[i].checked) {
actionType = i;
}
}

switch(actionType) {
case 0:
addNode();
break;
case 1:
if (currentPgraphCount > 0) {
delNode();
break;
}
case 2:
if (currentPgraphCount > 0) {
insertNode();
break;
}
case 3:
if (currentPgraphCount > 0) {
replaceNode();
break
}
default:
alert("No valid action was chosen");
}

document.getElementById("grafCount").options.length = 0;

for (i=0; i<nodeChangingArea.getElementsByTagName("p").length; i++) {


document.getElementById("grafCount").options[i] = new
Option(i+1);
}

return false;
}
Date:-
<html>
<head>
<title>Dynamic Date Display</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h1 id="dtField"></h1>
</body>
</html>

window.onload = initDate;

function initDate() {
var dayName = new Array("Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday");
var monName = new Array("January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November",
"December");

var now = new Date();


var thisMonth = now.getMonth() + 1;

var dtString = "Today is " + dayName[now.getDay()] + ", and the date


can be written as:<ul><li>";
dtString += monName[now.getMonth()] + " " + now.getDate() + ", " +
now.getFullYear() + "</li><li>";
dtString += now.getDate() + " " + monName[now.getMonth()] + " " +
now.getFullYear() + "</li><li>";
dtString += thisMonth + "-" + now.getDate() + "-" + now.getFullYear()
+ "</li><li>";
dtString += now.getDate() + "-" + thisMonth + "-" + now.getFullYear()
+ "</li></ul>";

document.getElementById("dtField").innerHTML = dtString;
}

RUNNING TIME:-
<html>
<head>
<title>JavaScript Clock</title>
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<div align="center">
<h2 id="showTime"> </h2>
</div>
</body>
</html>
window.onload = showTheTime;

function showTheTime() {
var now = new Date();

var theTime = showTheHours(now.getHours()) +


showZeroFilled(now.getMinutes()) + showZeroFilled(now.getSeconds()) +
showAmPm();
document.getElementById("showTime").innerHTML = theTime;
setTimeout("showTheTime()",1000);

function showTheHours(theHour) {
if (theHour == 0) {
return 12;
}
if (theHour < 13) {
return theHour;
}
return theHour-12;
}

function showZeroFilled(inValue) {
if (inValue > 9) {
return ":" + inValue;
}
return ":0" + inValue;
}

function showAmPm() {
if (now.getHours() < 12) {
return " am";
}
return " pm";
}
}

Shakespeare's Plays
Comedies

Tragedies
Histories

 Henry IV, Part 1


 Henry IV, Part 2

<html>
<head>
<title>Shakespeare's Plays</title>
<link rel="stylesheet" href="script.css" />
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h1>Shakespeare's Plays</h1>
<div>
<a href="menu1.html" class="menuLink">Comedies</a>
<ul class="menu" id="menu1">
<li><a href="pg1.html">All's Well That Ends
Well</a></li>
<li><a href="pg2.html">As You Like It</a></li>
<li><a href="pg3.html">Love's Labour's Lost</a></li>
<li><a href="pg4.html">The Comedy of Errors</a></li>
</ul>
</div>
<div>
<a href="menu2.html" class="menuLink">Tragedies</a>
<ul class="menu" id="menu2">
<li><a href="pg5.html">Anthony &amp; Cleopatra</a></li>
<li><a href="pg6.html">Hamlet</a></li>
<li><a href="pg7.html">Romeo &amp; Juliet</a></li>
</ul>
</div>
<div>
<a href="menu3.html" class="menuLink">Histories</a>
<ul class="menu" id="menu3">
<li><a href="pg8.html">Henry IV, Part 1</a></li>
<li><a href="pg9.html">Henry IV, Part 2</a></li>
</ul>
</div>
</body>
</html>

window.onload = initAll;

function initAll() {
var allLinks = document.getElementsByTagName("a");

for (var i=0; i<allLinks.length; i++) {


if (allLinks[i].className.indexOf("menuLink") > -1) {
allLinks[i].onclick = toggleMenu;
}
}
}

function toggleMenu() {
var startMenu = this.href.lastIndexOf("/")+1;
var stopMenu = this.href.lastIndexOf(".");
var thisMenuName = this.href.substring(startMenu,stopMenu);

var thisMenu = document.getElementById(thisMenuName).style;


if (thisMenu.display == "block") {
thisMenu.display = "none";
}
else {
thisMenu.display = "block";
}

return false;
}

<html>
<head>
<title>Shakespeare's Plays</title>
<link rel="stylesheet" href="script.css" />
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h1>Shakespeare's Plays</h1>
<div>
<a href="menu1.html" class="menuLink">Comedies</a>
<ul class="menu" id="menu1">
<li><a href="pg1.html">All's Well That Ends
Well</a></li>
<li><a href="pg2.html">As You Like It</a></li>
<li><a href="pg3.html">Love's Labour's Lost</a></li>
<li><a href="pg4.html">The Comedy of Errors</a></li>
</ul>
</div>
<div>
<a href="menu2.html" class="menuLink">Tragedies</a>
<ul class="menu" id="menu2">
<li><a href="pg5.html">Anthony &amp; Cleopatra</a></li>
<li><a href="pg6.html">Hamlet</a></li>
<li><a href="pg7.html">Romeo &amp; Juliet</a></li>
</ul>
</div>
<div>
<a href="menu3.html" class="menuLink">Histories</a>
<ul class="menu" id="menu3">
<li><a href="pg8.html">Henry IV, Part 1</a></li>
<li><a href="pg9.html">Henry IV, Part 2</a></li>
</ul>
</div>
</body>
</html>

window.onload = initAll;
function initAll() {
var allLinks = document.getElementsByTagName("a");

for (var i=0; i<allLinks.length; i++) {


if (allLinks[i].className.indexOf("menuLink") > -1) {
allLinks[i].onclick = retFalse;
allLinks[i].onmouseover = toggleMenu;
}
}
}

function toggleMenu() {
var startMenu = this.href.lastIndexOf("/")+1;
var stopMenu = this.href.lastIndexOf(".");
var thisMenuName = this.href.substring(startMenu,stopMenu);

document.getElementById(thisMenuName).style.display = "block";

this.parentNode.className = thisMenuName;
this.parentNode.onmouseout = toggleDivOff;
this.parentNode.onmouseover = toggleDivOn;
}

function toggleDivOn() {
document.getElementById(this.className).style.display = "block";
}

function toggleDivOff() {
document.getElementById(this.className).style.display = "none";
}

function retFalse() {
return false;
}

body {
background-color: white;
color: black;
}

div {
margin-bottom: 10px;
width: 180px;
background-color: #CF9;
float:left;
}

ul.menu {
display: none;
list-style-type: none;
margin: 0;
padding: 0;
}
ul.menu li {
font: 12px arial, helvetica, sans-serif;
padding-left: 10px;
}

a.menuLink, li a {
text-decoration: none;
color: #060;
}

a.menuLink {
font-size: 16px;
font-weight: bold;
}

li a:hover {
background-color: #060;
color: white;
}

<html>
<head>
<title>Our Summer Vacation!</title>
<link rel="stylesheet" href="script.css" />
<script type="text/javascript" src="script.js">
</script>
</head>
<body>
<h1>Our Summer Vacation Slideshow</h1>
<img height="240" width="320" src="images/slideImg0.jpg" alt="Our
Vacation Pix" id="slideshow" />
<div id="imgText"> &nbsp; </div>
<br clear="all" />
<form action="#">
<input type="button" id="prevLink" value="&laquo; Previous" />
<input type="button" id="nextLink" value="Next &raquo;" />
</form>
</body>
</html>

window.onload = initAll;

var currImg = 0;
var captionText = new Array(
"Our ship, leaving Vancouver.",
"We took a helicopter ride at our first port, Juneau.",
"The helicopter took us to Mendenhall Glacier.",
"The happy (and chilly) couple, on the glacier.",
"Here's what our second stop, Ketchikan, looked like from the ship.",
"We got to cruise through Glacier Bay. It was absolutely
breathtaking!",
"In Skagway, we took a train up into the mountains, all the way to the
Canadian Border.",
"Looking back down at Skagway from the train.",
"On a trip this romantic, I shouldn't have been surprised by a
proposal, but I was (obviously, I said yes).",
"It's nice to go on vacation, but it's nice to be home again, too."
)

function initAll() {
document.getElementById("imgText").innerHTML = captionText[0];
document.getElementById("prevLink").onclick = processPrevious;
document.getElementById("nextLink").onclick = processNext;
}

function processPrevious() {
newSlide(-1);
}

function processNext() {
newSlide(1);
}

function newSlide(direction) {
var imgCt = captionText.length;

currImg = currImg + direction;


if (currImg < 0) {
currImg = imgCt-1;
}
if (currImg == imgCt) {
currImg = 0;
}
document.getElementById("slideshow").src = "images/slideImg" + currImg
+ ".jpg";
document.getElementById("imgText").innerHTML = captionText[currImg];
}

body {
background-color: white;
color: black;
font: 12px verdana, arial, helvetica, sans-serif;
}

h1 {
font: 24px "trebuchet ms", verdana, arial, helvetica, sans-serif;
margin-left: 100px;
}

form {
margin-left: 100px;
}

#slideshow {
padding: 0 10px 10px 10px;
float: left;
}

#imgText {
padding: 10px 0 0 10px;
float: left;
width: 200px;
height: 150px;
border-color: black;
border-width: 1px 0 0 1px;
border-style: solid;
}

Você também pode gostar