Javascript Essentials Part 6

We shall discuss the following important issues relating to javascript.

  • Mouseover mouseout changes and Theme change
    - Change Link Color (Text change, Color change, both change)
    - Color Switch by css (background change)
    - Theme switch by css
  • Image Galleries
    - CJ motion gallery - left right mouse over scroll
    - Oncliking link image changes with fade in out - gallery (Captions & Image Transitions)
    - Compact Gallery
    - One popup for all images (Displaying changing images.)
    - One popup for all images (Displaying changing images and captions
  • More Form Effects
    - Form field highlight on focus
    - Form Field Select
    - Form field counter
    - Data appears or disappears on click and focus out

Mouseover mouseout changes

Change Link Color(Text change, Color change, both change)

This example explains how to change the link color and text on mouse over and out events.

Consider following script for mouse over and out events.

onMouseOver="this.innerHTML = 'The Software Tycoon'; this.style.color = '#ff0000';" onMouseOut="this.innerHTML = 'Microsoft'; this.style.color = '#0000ff';"

Full example:

<html>
<body>
<A HREF="http://www.microsoft.com/"
onMouseOver="this.style.color = '#ff0000';" onMouseOut="this.style.color = '#0000ff';">Microsoft</A>
<br><br>
<A HREF="http://www.microsoft.com/">
<FONT COLOR="#0000ff" onMouseOver="this.innerHTML = 'The Software Tycoon'; this.style.color = '#ff0000';" onMouseOut="this.innerHTML = 'Microsoft'; this.style.color = '#0000ff';">Microsoft</FONT></A>
<br>
<A HREF="http://www.microsoft.com/">
<FONT onMouseOver="this.innerHTML = 'The Software Tycoon'" onMouseOut="this.innerHTML = 'Microsoft'">Microsoft</FONT></A>
</body>
</html>

more reference at JavaScript Event Handlers - onmouseover and onmouseout

Color Switch by CSS (background change)

Download Color or CSS Switcher

Theme Switch by CSS

Another CSS changing, cookie based switcher.

Download Style Cookie Based Switcher

Image Galleries

CJ Motion Gallery with X-axis MouseOver Scroll

Left right scroll of images on mouse over. Clicking will open image in a new window.

Download CJ Motion Gallery

Oncliking Link and Image Changes with Fade In Out - Gallery (Captions and Image Transitions)

Very good light weighted example of images fade in out with changing images on clicking links or image thumbnails. Image position remains fix and next image fades in while previous fades out.

Download Gallery

Compact Gallery

In this gallery you can click at titles or captions to change description and image smoothly with transition.

Download Compact Gallery

One popup for all images (Displaying changing images.)

Here is a page having thumbnails. Clicking thumbnails will open image in a popup. Popup will server for all images.

Download Gallery

One popup for all images (Displaying changing images and captions

Here is a page having thumbnails. Clicking thumbnails will open image and its caption in a popup. Popup will server for all images and their captions.

Download Gallery

Form Effects

Form Field Highlight on Focus

Clicking form input field changes its background color.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="JavaScript1.2">
var highlightcolor="#cccccc"
var ns6=document.getElementById&&!document.all
var previous=''
var eventobj
var intended=/INPUT|TEXTAREA|SELECT|OPTION/
function checkel(which){
if (which.style&&intended.test(which.tagName)){
if (ns6&&eventobj.nodeType==3)
eventobj=eventobj.parentNode.parentNode
return true
}
else
return false
}
function highlight(e){
eventobj=ns6? e.target : event.srcElement
if (previous!=''){
if (checkel(previous))
previous.style.backgroundColor=''
previous=eventobj
if (checkel(eventobj))
eventobj.style.backgroundColor=highlightcolor
}
else{
if (checkel(eventobj))
eventobj.style.backgroundColor=highlightcolor
previous=eventobj
}
}
</script></head>
<body><form>
<p><input type="text" name="textfield" onKeyUp="highlight(event)" onClick="highlight(event)"></p>
<p><input type="text" name="textfield2" onKeyUp="highlight(event)" onClick="highlight(event)"></p>
<p><textarea name="textarea" cols="40" rows="5" onKeyUp="highlight(event)" onClick="highlight(event)"></textarea></p></form></body></html>
Form Field Select

Following script will enable you to click select form field data.

<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script language="Javascript">
<!--
/*
Select and Copy form element script- By Dynamicdrive.com
For full source, Terms of service, and 100s DTHML scripts
Visit http://www.dynamicdrive.com
*/
//specify whether contents should be auto copied to clipboard (memory)
//Applies only to IE 4+
//0=no, 1=yes
var copytoclip=1
function HighlightAll(theField) {
var tempval=eval("document."+theField)
tempval.focus()
tempval.select()
if (document.all&&copytoclip==1){
therange=tempval.createTextRange()
therange.execCommand("Copy")
window.status="Contents highlighted and copied to clipboard!"
setTimeout("window.status=''",1800)
}
}
//-->
</script>
</head>
<body>
<form name="sampleform1">
<a href="javascript:HighlightAll('sampleform1.kw')">Select All</a><br>
<textarea name="kw" id="johndoe" cols=55 rows=10></textarea>
</form></body></html>
Form Field Counter

Count and restrict input characters in form field.

<html><head>
<script type=text/javascript>
var ns6=document.getElementById&&!document.all
function restrictinput(maxlength,e,placeholder){
if (window.event&&event.srcElement.value.length>=maxlength)
return false
else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
var pressedkey=/[a-zA-Z0-9\.\,\/]/ //detect alphanumeric keys
if (pressedkey.test(String.fromCharCode(e.which)))
e.stopPropagation()
}
}
function countlimit(maxlength,e,placeholder){
var theform=eval(placeholder)
var lengthleft=maxlength-theform.value.length
var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
if (window.event||e.target&&e.target==eval(placeholder)){
if (lengthleft<0)
theform.value=theform.value.substring(0,maxlength)
placeholderobj.innerHTML=lengthleft
}
}
function displaylimit2(thename, theid, thelimit){
var theform=theid!=""? document.getElementById(theid) : thename
var limit_text='<b><span id="'+theform.toString()+'">'+thelimit+'</span></b> characters remaining on your input limit'
if (document.all||ns6)
document.write(limit_text)
if (document.all){
eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
}
else if (ns6){
document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
}
}
</script>
</head>
<body>
<form name=sampleform>
<textarea id=johndoe4 name=tt cols=55></textarea>
<br>
<script>displaylimit2("document.sampleform.johndoe4","",80)</script>
<form>
</body>
</html>
Data Appears or Disappears on Click and Focus Out in Form Input Field
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<form>
<p>
<input name="textfield" type="text" onFocus="if(this.value=='Select Me')this.value='';" value="Select Me">
</p>
<p>
<input name="textfield2" type="text" onFocus="if(this.value=='Click Here')this.value='';" onBlur="if(this.value=='')this.value='Click Here'" value="Click Here">
</p>
<p>
<input type="reset" name="Reset" value="Reset">
</p>
</form>
</body>
</html>

Download Form Effects and Controls

More Java Script Resources
Form Effects

http://www.dynamicdrive.com/dynamicindex16/

Javascript Rich Text Editors

http://www.dynamicdrive.com/dynamicindex16/richtexteditor/index.htm
Accept Terms
Submit Once
Remember entries 1
Remember entries 2, recall form values

Javascript Resources

http://www.dynamicdrive.com/
http://rainbow.arch.scriptmania.com/scripts/
http://www.allthescripts.com/category-7.html
http://www.codelifter.com/
http://www.qiksearch.com/
http://www.a1javascripts.com/
http://www.dhtmlshock.com/
http://www.hotscripts.com/JavaScript/index.html
http://www.webreference.com/js/
http://javascript.internet.com/
http://www.javascript.com/
http://www.scriptsearch.com/
http://www.codebrain.com/
http://www.codetoad.com/javascript/
http://webdeveloper.earthweb.com/webjs/
http://www.programmersheaven.com/zone29/index.htm
http://www.allthescripts.com/category-7.html
http://www.vicsjavascripts.org.uk/Home.htm

More Scrollers

http://www.dynamicdrive.com/dynamicindex10/text5.htm
http://www.dynamicdrive.com/dynamicindex2/crosstick.htm
http://www.dynamicdrive.com/dynamicindex2/emarquee.htm
http://www.dynamicdrive.com/dynamicindex2/cmarquee2.htm
http://www.dynamicdrive.com/dynamicindex2/cmarquee.htm
http://www.dynamicdrive.com/dynamicindex2/fadescroll.htm
http://www.dynamicdrive.com/dynamicindex2/scroller1.htm
http://www.dynamicdrive.com/dynamicindex2/dhtmlbillboard.htm
http://www.dynamicdrive.com/dynamicindex2/generaltick.htm
http://www.dynamicdrive.com/dynamicindex2/mikescroll.htm

Javascript Manuals

http://www.chmpdf.com/archives/ebooks/wrox/?file=Wrox…..pdf download
http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/

Javascript Essentials Part 5

Talk about form controls via Javascript. I have been hunting down js control over forms from the day I started web development. I love the control over programming and its essential too. Here in this javascript essentials part I will share with you some essential form controls.

  • Accept Terms & Go
  • Advanced Email Address Validator
  • Auto Drop Down List - Select from drop down and list updates accordingly
  • Auto Month DropDown with Date and Year
  • Auto Phone Number Format
  • Auto Tab
  • Character Counter
  • Check Un-check all from check boxes
  • Check Un-check all 2
  • Characters Disallow
  • Preview Image While Uploading
  • Submit Once

Accept Terms and Go

This script is about forcing user to click check box in order to accept terms or policy.

<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!-- Original:  Colin Pc  -->
<!-- Web Site:  http://www.insighteye.com/ -->
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Begin
function checkCheckBox(f){
if (f.agree.checked == false )
{
alert('Please check the box to continue.');
return false;
}else
return true;
}
//  End -->
</script>
</head>
<body>
<form action="www.tecnonascita.com" method="POST" onsubmit="return checkCheckBox(this)">
I accept: <input type="checkbox" value="0" name="agree">
<input type="submit" value="Continue Order">
<input type="button" value="Exit" onclick="document.location.href='backpage.html';">
</form>
</body>
</html>

Advanced Email Address Validator

<html>
<HEAD>
<script type="text/javascript">
function echeck(str) {
  var at="@"
  var dot="."
  var lat=str.indexOf(at)
  var lstr=str.length
  var ldot=str.indexOf(dot)
  if (str.indexOf(at)==-1){
     alert("Invalid E-mail ID")
     return false
  }
  if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
     alert("Invalid E-mail ID")
     return false
  }
  if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
      alert("Invalid E-mail ID")
      return false
  }
   if (str.indexOf(at,(lat+1))!=-1){
      alert("Invalid E-mail ID")
      return false
   }
   if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
      alert("Invalid E-mail ID")
      return false
   }
   if (str.indexOf(dot,(lat+2))==-1){
      alert("Invalid E-mail ID")
      return false
   }
   if (str.indexOf(" ")!=-1){
      alert("Invalid E-mail ID")
      return false
   }
   return true          
}
function ValidateForm(){
  var emailID=document.frmSample.txtEmail
 
  if ((emailID.value==null)||(emailID.value=="")){
    alert("Please Enter your Email ID")
    emailID.focus()
    return false
  }
  if (echeck(emailID.value)==false){
    emailID.value=""
    emailID.focus()
    return false
  }
  return true
 }
</script>
</HEAD>
<BODY>
<form name="frmSample" method="post" action="#" onSubmit="return ValidateForm()">
  <p>Enter an E-mail Address : 
    <input type="text" name="txtEmail">  
    <input type="submit" name="Submit" value="Submit">
  </p>
</form>
</body>
</html>

Auto Drop Down List - Select from drop down and list updates

<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
team = new Array(
new Array(
new Array("Saku Koivu", 39482304),
new Array("Martin Rucinsky", 34802389),
new Array("Jeff Hackett", 39823498),
new Array("Sheldon Sourray", 87587343),
new Array("Richard Zednik", 68798735),
new Array("Brian Savage", 98098509),
new Array("Stephane Robidas", 49490583),
new Array("Patrice Brisebois", 32898334),
new Array("Oleg Petrov", 92340934),
new Array("Chad Kilger", 34923409),
new Array("Benoit Brunet", 59384093),
new Array("Jan Bulis", 83948023),
new Array("Patrick Traverse", 41239812),
new Array("Jose Theodore", 98402398),
new Array("Craig Darby", 82393434),
new Array("Patric Poulin", 34290348),
new Array("Karl Dykhuis", 89092834)
),
new Array(
new Array("Mario Lemieux", 23840238),
new Array("Jaromir Jagr", 92390484),
new Array("Robert Lang", 29048203),
new Array("Alexei Kovalev", 94098230),
new Array("Jean-Sebastien Aubin", 39234923),
new Array("Kevin Stevens", 29345423)
),
null,
new Array(
new Array("Alexei Yashin", 20394802),
new Array("Daniel Alfredson", 34982039),
new Array("Marian Hossa", 92348902),
new Array("Patrick Lalime", 98203894),
new Array("Radek Bonk", 98234902)
)
);
function fillSelectFromArray(selectCtrl, itemArray, goodPrompt, badPrompt, defaultItem) {
var i, j;
var prompt;
// empty existing items
for (i = selectCtrl.options.length; i >= 0; i--) {
selectCtrl.options[i] = null; 
}
prompt = (itemArray != null) ? goodPrompt : badPrompt;
if (prompt == null) {
j = 0;
}
else {
selectCtrl.options[0] = new Option(prompt);
j = 1;
}
if (itemArray != null) {
// add new items
for (i = 0; i < itemArray.length; i++) {
selectCtrl.options[j] = new Option(itemArray[i][0]);
if (itemArray[i][1] != null) {
selectCtrl.options[j].value = itemArray[i][1]; 
}
j++;
}
// select first item (prompt) for sub list
selectCtrl.options[0].selected = true;
   }
}
//  End -->
</script>
</HEAD>
<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->
<BODY>
<FORM NAME="main">
<SELECT NAME="Make" onChange="fillSelectFromArray(this.form.Team, ((this.selectedIndex == -1) ? null : team[this.selectedIndex-1]));">
<OPTION VALUE="-1">Select Team
<OPTION VALUE=1>Montreal Canadiens
<OPTION VALUE=2>Pittsburg Penguins
<OPTION VALUE=3>Toronto Maple Leafs
<OPTION VALUE=4>Ottawa Senators
</SELECT>
<BR>
<SELECT NAME="Team" SIZE="5">
<OPTION></OPTION>
<OPTION></OPTION>
<OPTION></OPTION>
<OPTION></OPTION>
<OPTION></OPTION>
</SELECT>
</FORM>
</body>
</html>

Auto Month Drop Down with Date and Year

This script will make your life easirer by auto populating date, month and year range to select.

<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
today = new Date();
thismonth = today.getMonth()+1;
thisyear = today.getYear();
thisday = today.getDate();
montharray=new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
maxdays=montharray[thismonth-1];
if (thismonth==2) {
if ((thisyear/4)!=parseInt(thisyear/4)) maxdays=28;
else maxdays=29;
}
thismonth = "" + thismonth
if (thismonth.length == 1) {
thismonth = "0" + thismonth;
}
document.write("<form>");
document.write("<select name=dates size=1>");
for (var theday = 1; theday <= maxdays; theday++) {
var theday = "" + theday;
if (theday.length == 1) {
theday = "0" + theday;
}
document.write("<option");
if (theday == thisday) document.write(" selected");
document.write(">");
document.write(thismonth + "-" + theday + "-" + thisyear);
}
document.write("</select></form>");
// End -->
</SCRIPT>

Auto Phone Number Format While User Types In

As you write phone number in text input box, this script will format it and give user an idea about how to write phone number.
i.e.
If user will write 300-4269752
It will convert it into (300)426-9752 live.

<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var n;
var p;
var p1;
function ValidatePhone(){
p=p1.value
if(p.length==3){
	//d10=p.indexOf('(')
	pp=p;
	d4=p.indexOf('(')
	d5=p.indexOf(')')
	if(d4==-1){
		pp="("+pp;
	}
	if(d5==-1){
		pp=pp+")";
	}
	//pp="("+pp+")";
	document.frmPhone.txtphone.value="";
	document.frmPhone.txtphone.value=pp;
}
if(p.length>3){
	d1=p.indexOf('(')
	d2=p.indexOf(')')
	if (d2==-1){
		l30=p.length;
		p30=p.substring(0,4);
		//alert(p30);
		p30=p30+")"
		p31=p.substring(4,l30);
		pp=p30+p31;
		//alert(p31);
		document.frmPhone.txtphone.value="";
		document.frmPhone.txtphone.value=pp;
	}
	}
if(p.length>5){
	p11=p.substring(d1+1,d2);
	if(p11.length>3){
	p12=p11;
	l12=p12.length;
	l15=p.length
	//l12=l12-3
	p13=p11.substring(0,3);
	p14=p11.substring(3,l12);
	p15=p.substring(d2+1,l15);
	document.frmPhone.txtphone.value="";
	pp="("+p13+")"+p14+p15;
	document.frmPhone.txtphone.value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
	l16=p.length;
	p16=p.substring(d2+1,l16);
	l17=p16.length;
	if(l17>3&&p16.indexOf('-')==-1){
		p17=p.substring(d2+1,d2+4);
		p18=p.substring(d2+4,l16);
		p19=p.substring(0,d2+1);
		//alert(p19);
	pp=p19+p17+"-"+p18;
	document.frmPhone.txtphone.value="";
	document.frmPhone.txtphone.value=pp;
	//obj1.value="";
	//obj1.value=pp;
	}
}
//}
setTimeout(ValidatePhone,100)
}
function getIt(m){
n=m.name;
//p1=document.forms[0].elements[n]
p1=m
ValidatePhone()
}
function testphone(obj1){
p=obj1.value
//alert(p)
p=p.replace("(","")
p=p.replace(")","")
p=p.replace("-","")
p=p.replace("-","")
//alert(isNaN(p))
if (isNaN(p)==true){
alert("Check phone");
return false;
}
}
//  End -->
</script>
</HEAD>
<BODY>
<div align="center">
<form name=frmPhone>
<font size="4" color="#0000FF"><b>Enter Telephone Number</b></font><br>
(To refresh, hold down shift and press the browser refresh button)<br>
<input type=text name=txtphone maxlength="13" onclick="javascript:getIt(this)" >
</form>
</div>
</body>
</html>

Auto Tab

This script is about auto tabbing in forms. As you type in one text input field and when required values have been put into the box, then cursor control will shift into next input box.

<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var isNN = (navigator.appName.indexOf("Netscape")!=-1);
function autoTab(input,len, e) {
var keyCode = (isNN) ? e.which : e.keyCode; 
var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
if(input.value.length >= len && !containsElement(filter,keyCode)) {
input.value = input.value.slice(0, len);
input.form[(getIndex(input)+1) % input.form.length].focus();
}
function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}
function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}
//  End -->
</script>
</HEAD>
<BODY>
<center>
<form>
<table>
<tr>
<td>Phone Number : <br>
1 - (
<small><input onKeyUp="return autoTab(this, 3, event);" size="4" maxlength="3"></small>) - 
<small><input onKeyUp="return autoTab(this, 3, event);" size="4" maxlength="3"></small> - 
<small><input onKeyUp="return autoTab(this, 4, event);" size="5" maxlength="4"></small>
</td>
</tr>
<tr>
<td>Social Security Number : <br>
<small><input onKeyUp="return autoTab(this, 3, event);" size="4" maxlength="3"></small> - 
<small><input onKeyUp="return autoTab(this, 2, event);" size="3" maxlength="2"></small> - 
<small><input onKeyUp="return autoTab(this, 4, event);" size="5" maxlength="4"></small>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>

Character Counter

This script will count words as you will type in the input box and will tell you that how many characters have left to type. It will restrict you from typing more then allowed characters.

<html>
<HEAD>
<script type="text/javascript">
<!--
function getObject(obj) {
  var theObj;
  if(document.all) {
    if(typeof obj=="string") {
      return document.all(obj);
    } else {
      return obj.style;
    }
  }
  if(document.getElementById) {
    if(typeof obj=="string") {
      return document.getElementById(obj);
    } else {
      return obj.style;
    }
  }
  return null;
}
 
//Contador de caracteres.
function Contar(entrada,salida,texto,caracteres) {
  var entradaObj=getObject(entrada);
  var salidaObj=getObject(salida);
  var longitud=caracteres - entradaObj.value.length;
  if(longitud <= 0) {
    longitud=0;
    texto='<span class="disable"> '+texto+' </span>';
    entradaObj.value=entradaObj.value.substr(0,caracteres);
  }
  salidaObj.innerHTML = texto.replace("{CHAR}",longitud);
}
 
//-->
</script>
<style type="text/css">
<!--
BODY {
  font-family: Arial, Verdana, Geneva, Helvetica, sans-serif;
  font-size: 11px;
  font-weight: bold;
  color: Black;
  margin-left: 0px;
  margin-right: 0px;
  background-color: White;
}
.minitext {
  font-family: Arial, Verdana, Geneva, Helvetica, sans-serif;
  font-size: 8pt;
  font-weight: normal;
  color: Black;
}
 
.0 {
  background-color: #4786D2;
}
.1 {
  background-color: #D3E8FD;
}
.2 {
  background-color: #D3E8FD;
}
.3 {
  background-color: #D3E8FD;
}
.4 {
  background-color: #D3E8FD;
}
 
TABLE {
  font-family: Arial, Verdana, Geneva, Helvetica, sans-serif;
  font-size: 11px;
  font-weight: bold;
  color: Black;
}
 
INPUT.text {
  background-color: #FFFFFF;
  color: Black;
  border: 2px ridge Black;
  font-size: 10px;
  font-family: Verdana, Arial;
  font-weight: normal;
}
 
.enable {
  background-color: #77FF77;
  font-weight: bold;
  color: Black;
}
.disable {
  background-color: #FF7777;
  font-weight: bold;
  color: Black;
}
-->
</style>
</HEAD>
<BODY>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<form action="#" method="post">
<table align="center" class="0" border="0" cellspacing="1" cellpadding="5">
  <tr>
    <td align="right" class="1"><span class="options">Field Name</span></td>
    <td class="2"><INPUT TYPE="TEXT" class="text" id="eBann" name="bannerURL" maxlength="100" size="60" onKeyUp="Contar('eBann','sBann','{CHAR} characters left.',100);"><br><span id="sBann" class="minitext">100 characters left.</span></td>
  </tr>
</table>
</form>
</body>
</html>

Check Un-Check All From Check Boxes

Check or un-check check boxes by a single button.

<html>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var checkflag = "false";
function check(field) {
if (checkflag == "false") {
for (i = 0; i < field.length; i++) {
field[i].checked = true;}
checkflag = "true";
return "Uncheck All"; }
else {
for (i = 0; i < field.length; i++) {
field[i].checked = false; }
checkflag = "false";
return "Check All"; }
}
</script>
</HEAD>
<BODY>
<center>
<form name=myform action="" method=post>
<table>
<tr><td>
<b>Your Favorite Scripts & Languages</b><br>
<input type=checkbox name=list value="1">Java<br>
<input type=checkbox name=list value="2">JavaScript<br>
<input type=checkbox name=list value="3">ASP<br>
<input type=checkbox name=list value="4">HTML<br>
<input type=checkbox name=list value="5">SQL<br>
<br>                                                    
<input type=button value="Check All" onClick="this.value=check(this.form.list)"> 
</td></tr>
</table>
</form>
</center>
</body>
</html>

Check Uncheck All - By Check Box

Instead of button we can use a check box to check or un-check all boxes.

<html>
<HEAD>
<script type="text/javascript">
function checkAll(checkname, exby) {
  for (i = 0; i < checkname.length; i++)
  checkname[i].checked = exby.checked? true:false
}
</script>
</HEAD>
<BODY>
<form name ="mylist">
  <input type="checkbox" name="checkGroup" value ="first">First<br>
  <input type="checkbox" name="checkGroup" value ="second">Second<br>
  <input type="checkbox" name="checkGroup" value ="third">Third<br>
  <input type="checkbox" name="checkGroup" value ="fourth">Fourth<br>
  <input type="checkbox" name="all" onClick="checkAll(document.mylist.checkGroup,this)">Check/Uncheck All<br>
</form>
</body>
</html>

Characters Disallow - Restrict user from typing some characters

We can disallow some characters like sign of exclamation, at the rate of and others like estaric to type in text fields. Sometimes we do not want single or double quotes in input field. It is also good for security purpose. We can allow just characters or numbers or just alphabets in text field.

<html>
<BODY>
<center>
<script>
var isNS4 = (navigator.appName=="Netscape")?1:0;
</script>
<form onSubmit="return false;">
This field will not accept special characters: (like !@#$%^&* etc)<br>
<textarea rows=2 cols=20 name=comments onKeypress="if(!isNS4){if ((event.keyCode > 32 && event.keyCode < 48) || (event.keyCode > 57 && event.keyCode < 65) || (event.keyCode > 90 && event.keyCode < 97)) event.returnValue = false;}else{if ((event.which > 32 && event.which < 48) || (event.which > 57 && event.which < 65) || (event.which > 90 && event.which < 97)) return false;}"></textarea>
<br><br>
This field will not accept double or single quotes:<br>
<input type=text name=txtEmail onKeypress="if(!isNS4){if (event.keyCode==34 || event.keyCode==39) event.returnValue = false;}else{if (event.which==34 || event.which==39) return false;}">
<br><br>
This field will only accept numbers:<br>
<input type=text name=txtPostalCode onKeypress="if(!isNS4){if(event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;}else{if(event.which < 45 || event.which > 57) returnfalse;}">
</form>
</center>
</body>
</html>

Preview Image While Uploading

We can preview image before uploading. While user browse an image file and puts in a file field, we can offer him preview by displaying a thumbnail of image using javascript to show him what he is going to upload.

<html>
<HEAD>
<script type="text/javascript">
/***** CUSTOMIZE THESE VARIABLES *****/
  // width to resize large images to
var maxWidth=100;
  // height to resize large images to
var maxHeight=100;
  // valid file types
var fileTypes=["bmp","gif","png","jpg","jpeg"];
  // the id of the preview image tag
var outImage="previewField";
  // what to display when the image is not valid
var defaultPic="spacer.gif";
/***** DO NOT EDIT BELOW *****/
function preview(what){
  var source=what.value;
  var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
  for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
  globalPic=new Image();
  if (i<fileTypes.length) globalPic.src=source;
  else {
    globalPic.src=defaultPic;
    alert("THAT IS NOT A VALID IMAGE\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", "));
  }
  setTimeout("applyChanges()",200);
}
var globalPic;
function applyChanges(){
  var field=document.getElementById(outImage);
  var x=parseInt(globalPic.width);
  var y=parseInt(globalPic.height);
  if (x>maxWidth) {
    y*=maxWidth/x;
    x=maxWidth;
  }
  if (y>maxHeight) {
    x*=maxHeight/y;
    y=maxHeight;
  }
  field.style.display=(x<1 || y<1)?"none":"";
  field.src=globalPic.src;
  field.width=x;
  field.height=y;
}
// End -->
</script>
</HEAD>
<BODY>
<div align="center" style="line-height: 1.9em;">
Test it by locating a valid file on your hard drive:
<br>
<input type="file" id="picField" onchange="preview(this)">
<br>
<img alt="Graphic will preview here" id="previewField" src="spacer.gif">
<br> <div style="font-size: 7pt;"></div>
</div>
</body>
</html>

Submit Once

Disable submit button when user have hit it once to disallow submitting the form again.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<html>
<body>
<script type="" language="javascript">
	//add function which disables the form upon submit press
	allowSubmit = true;	
	function disableForm() {
		for ( var i = 0; i < document.forms.length ; i++) {
			for ( var j = 0; j < document.forms[i].length ; j++) {
				var formElement = document.forms[i].elements[j];	
				formElement.style.color = '#999999';
				formElement.readOnly = true;	
			}
		}
		var allow = allowSubmit;
		allowSubmit = false;
		return allow;
	}
</script>
This is the form:</br>
<form method="post" action="somepage.html" onsubmit="return disableForm();">
<input type="text"/>
<input type="submit" value="Submit Information"/>
</form>
</body>
</html>

Following is the file containing all the above described scripts in example form, ready to use.

Download Form Related All Above Mentioned Scripts

Javascript Essentials Part 4

We will cover following essentials of javascript in this area.

  • TOOLTIPS
    - Moving Tooltips
    - Hint Tooltip
    - Fade in out Tooltip
    - Regular Tooltip
  • DATE & TIME
    - Regular Time & Date Full Script (Live)
    - Date Script (Month, Date, Year)
    - Time Script (Time(Hour,minutes,second), AM:PM) - Live
  • Rotation
    - Image Rotation (Page Reload or Refresh Based)
    - Text Rotation (Page Reload or Refresh Based)
    - Image Rotation (Daily)
    - Image Rotation (After some seconds) - Appear
    - Image Rotation (After some seconds) - Fade in out
  • Form Validation
    - By Simple Body and Head Section Script Method
    - By External js Validator File
  • Scrollers (marquee and advanced)
    - Scroll Control by an external js File
    - Simple Scroll
    - Continuous Scroll
  • Text and Image Loading
    - Loading by text (till all page loads)
    - Loading by image

TOOLTIPS

Moving Tooltips
<head>
<script language="JavaScript">
<!--
self.moveTo(0,0)
self.resizeTo(screen.availWidth,screen.availHeight)
//-->
</script>
</head>
<body>
<DIV id=dek style="Z-INDEX: 1; VISIBILITY: hidden; POSITION: absolute"></DIV>
  <SCRIPT language="" type=text/javascript>
<!--
Xoffset=  20;    // modify these values to ...
Yoffset= 10;    // change the popup position.
var old,skn,iex=(document.all),yyy=-550;
var ns4=document.layers
var ns6=document.getElementById&&!document.all
var ie4=document.all
if (ns4)
skn=document.dek
else if (ns6)
skn=document.getElementById("dek").style
else if (ie4)
skn=document.all.dek.style
if(ns4)document.captureEvents(Event.MOUSEMOVE);
else{
skn.visibility="visible"
skn.display="none"
}
document.onmousemove=get_mouse;
function popup(msg,bak){
var content="<TABLE  WIDTH=200 BORDER=0 BORDERCOLOR=#4F1919 CELLPADDING=3 CELLSPACING=0 "+
"BGCOLOR="+bak+"><TD ALIGN=center><FONT COLOR=ffffff SIZE=1 face=Verdana, Arial, Helvetica, sans-serif>"+ msg +"</FONT></TD></TABLE>";
yyy=Yoffset;
 if(ns4){skn.document.write(content);skn.document.close();skn.visibility="visible";}
 if(ns6){document.getElementById("dek").innerHTML=content;skn.display='';}
 if(ie4){document.all("dek").innerHTML=content;skn.display='';}
}
function get_mouse(e){
var x=(ns4||ns6)?e.pageX:event.x+document.body.scrollLeft;
skn.left=x+Xoffset;
var y=(ns4||ns6)?e.pageY:event.y+document.body.scrollTop;
skn.top=y+yyy;
}
function kill(){
yyy=-1000;
if(ns4){skn.visibility="hidden";}
else if (ns6||ie4)
skn.display="none";
}
// -->
</SCRIPT>
<a onmouseover="popup('.enter static, non-flash, non animated website :)','#840000')" onmouseout=kill() href="index1.htm" target="_self">
<img src="20040410-300x250-blank.jpg" width="100" height="50" border="0"></a>

Download Moving Tool Tip

Hint Tooltip

This tool tip is for hint purpose and appears by clicking at some link.

Download Hint Tooltip Script

Fade in out Tooltip

http://www.dynamicdrive.com/dynamicindex5/linkinfo2.htm

Regular Tooltip

Image tool tip is by alt tag and text tooltip is by title tag.

<a href="#" title="here is tooltip text">some link</a>
<img src="someimage.jpg" alt="tooltip text">

DATE and TIME

Regular Time and Date Full Script (Live)
<script language="JavaScript">
function tS(){ x=new Date(tN().getUTCFullYear(),tN().getUTCMonth(),tN().getUTCDate(),tN().getUTCHours(),tN().getUTCMinutes(),tN().getUTCSeconds()); x.setTime(x.getTime()+18000000); return x; } 
function tN(){ return new Date(); } 
function lZ(x){ return (x>9)?x:'0'+x; } 
function tH(x){ if(x==0){ x=12; } return (x>12)?x-=12:x; } 
function dT(){ if(fr==0){ fr=1; document.write('<span id="tP">'+eval(oT)+'</span>'); } tP.innerText=eval(oT); setTimeout('dT()',1000); } 
function aP(x){ return (x>11)?'pm':'am'; } 
function y4(x){ return (x<500)?x+1900:x; } 
var dN=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'),mN=new Array('January','February','March','April','May','June','July','August','September','October','November','December'),fr=0,oT="dN[tS().getDay()]+' '+tS().getDate()+' '+mN[tS().getMonth()]+' '+y4(tS().getYear())+' '+':'+':'+' '+tH(tS().getHours())+':'+lZ(tS().getMinutes())+':'+lZ(tS().getSeconds())+' '+aP(tS().getHours())";
</script> 
<script language="JavaScript">
dT();
</script>
Date Script (Month, Date, Year)
<script language=JavaScript>
var months=new Array(13);months[1]="January";months[2]="February";
months[3]="March";months[4]="April";months[5]="May";months[6]="June";
months[7]="July";months[8]="August";months[9]="September";months[10]="October";
months[11]="November";months[12]="December";var time=new Date();
var lmonth=months[time.getMonth() + 1];var date=time.getDate();
var year=time.getYear();
if ((navigator.appName == "Microsoft Internet Explorer") && (year < 2000))
year="19" + year;if (navigator.appName == "Netscape")year=1900 + year;
document.write(lmonth + " ");
document.write(date + ", " + year);
</script>
Time script (Time(Hour,minutes,second), AM:PM) - Live
<SCRIPT>
function tick() {
var hours, minutes, seconds, ap;
var intHours, intMinutes, intSeconds;
var today;
today = new Date();
intHours = today.getHours();
intMinutes = today.getMinutes();
intSeconds = today.getSeconds();
if (intHours == 0) {
hours = "12:";
ap = "It's midnight";
} else if (intHours < 12) {
hours = intHours+":";
ap = " AM";
} else if (intHours == 12) {
hours = "12:";
ap = "It's noon";
} else {
intHours = intHours - 12
hours = intHours + ":";
ap = " PM";
}
if (intMinutes < 10) {
minutes = "0"+intMinutes+":";
} else {
minutes = intMinutes+":";
}
if (intSeconds < 10) {
seconds = "0"+intSeconds+" ";
} else {
seconds = intSeconds+" ";
}
timeString = hours+minutes+seconds+ap;
Clock.innerHTML = timeString;
window.setTimeout("tick();", 100);
}
window.onload = tick;
</SCRIPT>
<DIV id=Clock style="FONT-FAMILY: Verdana; FONT-SIZE: 10pt"> </DIV>

Rotation

Image Rotation (Page Reload or Refresh Based)
<SCRIPT LANGUAGE="Javascript"> function image() {
};
image = new image();
number = 0;
// imageArray
image[number++] = "<img src='images/1u.gif' border='0'>"
image[number++] = "<img src='images/2u.gif' border='0'>"
image[number++] = "<img src='images/3u.gif' border='0'>"
image[number++] = "<img src='images/4u.gif' border='0'>"
image[number++] = "<img src='images/5u.gif' border='0'>"
image[number++] = "<img src='images/6u.gif' border='0'>"
image[number++] = "<img src='images/7u.gif' border='0'>"
image[number++] = "<img src='images/8u.gif' border='0'>"
image[number++] = "<img src='images/9u.gif' border='0'>"
image[number++] = "<img src='images/10u.gif' border='0'>"
image[number++] = "<img src='images/11u.gif' border='0'>"
image[number++] = "<img src='images/12u.gif' border='0'>"
image[number++] = "<img src='images/13u.gif' border='0'>"
image[number++] = "<img src='images/14u.gif' border='0'>"
image[number++] = "<img src='images/15u.gif' border='0'>"
image[number++] = "<img src='images/16u.gif' border='0'>"
image[number++] = "<img src='images/17u.gif' border='0'>"
image[number++] = "<img src='images/18u.gif' border='0'>"
image[number++] = "<img src='images/19u.gif' border='0'>"
image[number++] = "<img src='images/20u.gif' border='0'>"
image[number++] = "<img src='images/21u.gif' border='0'>"
// keep adding items here...
increment = Math.floor(Math.random() * number);
document.write(image[increment]);
</SCRIPT>
Text Rotation (Page Reload or Refresh Based)
<SCRIPT LANGUAGE="Javascript">
function makeQuote() {
if((navigator.userAgent.indexOf("Mozilla/3.0") != -1) ||
(navigator.userAgent.indexOf("MSIE")!= -1)) {
Quotes = new Array();
Quotes[0] = "\"Whatever good(O man!) happens to thee is from Allah;\<BR>but whatever evil happens to thee is from thy(own)soul.";
Quotes[1] = "\And we have sent thee as an Apostle to (instruct) mankind;\<BR>and enough is Allah for a witness.";
Quotes[2] = "\Freedom without discipline;\<BR>is a disastrous.";
Quotes[3] = "\We must know that life is difficult,if we know and\<BR>accept it, it is no longer dificult.";
Quotes[4] = "\Instead of worrying about things and events that you can't control,\<BR>start focusing on things u can control.";
Quotes[5] = "\Know that u are a miracle yourself\<BR>and are empowered to do miracles.";
Quotes[6] = "\Problems and uncertainties\<BR>keep the life going.";
Quotes[7] = "\Throw the word impossible out of\<BR>ur dictionary.Never ever give up.";
Quotes[8] = "\You can be anything, you want ,\<BR>if u are willing to pay its price.";
Quotes[9] = "\You can be anything\<BR>but not everything."; var x = Math.floor(Quotes.length * Math.random());
document.writeln(Quotes[x]);
}
}
</SCRIPT>
<SCRIPT LANGUAGE="javascript">
makeQuote();
</SCRIPT>
Image Rotation (Daily)
<!-- Paste this code into the BODY of your HTML document -->
<SCRIPT LANGUAGE="JavaScript">
today = new Date();
day = today.getDay();
arday = new Array("sunday.jpg", "monday.jpg", "tuesday.jpg", 
"wednesday.jpg", "thursday.jpg", "friday.jpg", "saturday.jpg");
document.write("<img src='" + arday[day] + "'>");
</SCRIPT>
Image Rotation (After some seconds) - Appear

Image rotation by java script. Image changes after some seconds.

Download Image Transition Effect Using Javascript

Image Rotation (After some seconds) - Fade in out

Download Image Transition Fade In out Effect

Form Validation

By simple body and head section script method

Put the following script in body section. On hitting submit button, form returns function CheckData which validates input fields.

<form name="quickmessage" action="somepage.php" method="POST" onSubmit="return CheckData()">
<input name="name" type="text" class="formsecond" id="name">
<input name="email" type="text" class="formsecond" id="email">
<input name="phone" type="text" class="formsecond" id="phone">
<textarea name="message" rows="5" class="formsecond2" id="message"></textarea>
<input name="Submit2" type="reset" class="button" value="Reset"> 
<input name="Submit3" type="submit" class="button" value="Submit">
</form>

Put the following script in head section of web page.

<script language="javascript">
function isValidEmail(str) {
return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}
function CheckData()
{
with(document.quickmessage)
{
if(name.value == "")
{
alert("Please enter your name.");
name.focus();
return false;
}
if(email.value == "")
{
alert("Please enter your email address.");
email.focus();
return false;
}
if (!isValidEmail(email.value)) 
{
alert("Please enter a valid email address");
return false;
}
if(phone.value == "")
{
alert("Please enter your phone number.");
phone.focus();
return false;
}
if(message.value == "")
{
alert("Please enter Message/Query.");
message.focus();
return false;
}
}
return true;
}
</script>
By external js validator file

Following example uses an external js file to validate form input fields.

Download Form Validation Method

Scrollers (marquee and advanced)

Scroll by an external js file control new

in this example images are in images folder with names product-1.jpg, product-2.jpg, product-3.jpg and in quantity 3. This method will preload images, call them and make them scroll with onmouseover stop event.

Create a folder in root, name it scripts, make a gallery.js file in it and write in that following code.

// preload images
var Gallery = new Array( ); for (var i = 0; i < 3; i++)
{
Gallery[i] = new Image( );
Gallery[i].src = ("images/product-" + (i + 1) + ".jpg");
}
document.write('<marquee style="width:140px; height:380px;" scrollamount="2" scrolldelay="20" direction="up" onmouseover="this.stop( ); return true;" onmouseout="this.start( ); return true;">');
for (var j = 1; j<= 3; j ++)
{
document.write(' <img src="images/product-' + j + '.jpg" width="120" height="120" alt="" title="">');
document.write(' <br><br>');
}
document.write('</marquee>');

Change the blue text according to requirement.

Where you want this scroll to appear , there in page call that js file by doing the following.

<script language="javascript" src="scripts/gallery.js"></script>

This is global method and you can call by this, any set of images in any sequence or direction at any page of the site.

Download Easy JS Scroll

Simple Scroll

Use this marquee for any table or any text with linkage on it and stop and play control.

<MARQUEE onmouseover=this.stop(); onmouseout=this.start(); scrollAmount=1 scrollDelay=5 direction=up width=140 height=100>text or content to be scrolled</MARQUEE>
Continuous Scroll - No breaks between data

This scroll is continuous scroll and does exactly what names is suggesting. If it is vertical and data elements aer 4 then it will add a chain kind of scroll and after 4 element you will see first one appearing and there will be no breaks in scroll. That… :) I love this script. Simple and easy to use, a useful and functional javascript scroll.

Download Continuous Scroll Script

Text and image loading

Loading by text (till all page loads) and Image

Till page loads it shows loading text or image. While the page is loading it is nice to show viewers some text saying loading… or any image showing loading state in a stylish way.

Download Script

Javascript Essentials Part 3

I have selected some very very essential scripts based on javascript which are widely and mostly used in everyday website. I have been also using these for years and it seems like these will never get old and will be always wanted by web developers. I started a series of Javascript Essentials and this is the third episode regarding that. Hope everybody will find these extremely useful.

I will answer to the following most wanted requirements in javascript here:

  • Tab Content Script - Switching Menu Like Yahoo
  • External JS Switcher
  • Jump Menu Switching
    (Radio buttons select and jump menu content changes)
  • Right Click Menu-IE5.5+
  • Featureless Window - Pop up window with custom properties
  • Button Pop-Up
  • Pop-Up - Body Based
  • Pop-Up Using Head and Body of Web page
  • Pop-Up window maker
  • Pop-Up Box - On Load - Cross Browser
  • Focus (Window Focus)
  • Jump to Top Sliding Scrolling Button

Tab Content Script - switching menu like yahoo

Head CSS Section
<style type="text/css">
#tablist{
padding: 3px 0;
margin-left: 0;
margin-bottom: 0;
margin-top: 0.1em;
font: bold 12px Verdana;
}
#tablist li{
list-style: none;
display: inline;
margin: 0;
}
#tablist li a{
padding: 3px 0.5em;
margin-left: 3px;
border: 1px solid #778;
border-bottom: none;
background: white;
}
#tablist li a:link, #tablist li a:visited{
color: navy;
}
#tablist li a.current{
background: lightyellow;
}
#tabcontentcontainer{
width: 400px;
/* Insert Optional Height definition here to give all the content a unified height */
padding: 5px;
border: 1px solid black;
}
.tabcontent{
display:none;
}
</style> <script type="text/javascript">
//Set tab to intially be selected when page loads:
//[which tab (1=first tab), ID of tab content to display]:
var initialtab=[1, "sc1"]
////////Stop editting////////////////
function cascadedstyle(el, cssproperty, csspropertyNS){
if (el.currentStyle)
return el.currentStyle[cssproperty]
else if (window.getComputedStyle){
var elstyle=window.getComputedStyle(el, "")
return elstyle.getPropertyValue(csspropertyNS)
}
}
var previoustab=""
function expandcontent(cid, aobject){
if (document.getElementById){
highlighttab(aobject)
detectSourceindex(aobject)
if (previoustab!="")
document.getElementById(previoustab).style.display="none"
document.getElementById(cid).style.display="block"
previoustab=cid
if (aobject.blur)
aobject.blur()
return false
}
else
return true
}
function highlighttab(aobject){
if (typeof tabobjlinks=="undefined")
collecttablinks()
for (i=0; i<tabobjlinks.length; i++)
tabobjlinks[i].style.backgroundColor=initTabcolor
var themecolor=aobject.getAttribute("theme")? aobject.getAttribute("theme") : initTabpostcolor
aobject.style.backgroundColor=document.getElementById("tabcontentcontainer").style.backgroundColor=themecolor
}
function collecttablinks(){
var tabobj=document.getElementById("tablist")
tabobjlinks=tabobj.getElementsByTagName("A")
}
function detectSourceindex(aobject){
for (i=0; i<tabobjlinks.length; i++){
if (aobject==tabobjlinks[i]){
tabsourceindex=i //source index of tab bar relative to other tabs
break
}
}
}
function do_onload(){
var cookiename=(typeof persisttype!="undefined" && persisttype=="sitewide")? "tabcontent" : window.location.pathname
var cookiecheck=window.get_cookie && get_cookie(cookiename).indexOf("|")!=-1
collecttablinks()
initTabcolor=cascadedstyle(tabobjlinks[1], "backgroundColor", "background-color")
initTabpostcolor=cascadedstyle(tabobjlinks[0], "backgroundColor", "background-color")
if (typeof enablepersistence!="undefined" && enablepersistence && cookiecheck){
var cookieparse=get_cookie(cookiename).split("|")
var whichtab=cookieparse[0]
var tabcontentid=cookieparse[1]
expandcontent(tabcontentid, tabobjlinks[whichtab])
}
else
expandcontent(initialtab[1], tabobjlinks[initialtab[0]-1])
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload
</script>
Body Section
<ul id="tablist">
<li><a href="http://www.dynamicdrive.com" class="current" onClick="return expandcontent('sc1', this)">Dynamic Drive</a></li>
<li><a href="new.htm" onClick="return expandcontent('sc2', this)" theme="#EAEAFF">What's New</a></li>
<li><a href="hot.htm" onClick="return expandcontent('sc3', this)" theme="#FFE6E6">What's Hot</a></li>
<li><a href="search.htm" onClick="return expandcontent('sc4', this)" theme="#DFFFDF">Search</a></li>
</ul> <DIV id="tabcontentcontainer">
<div id="sc1" class="tabcontent">
Visit Dynamic Drive for free, award winning DHTML scripts for your site:<br />
</div>
<div id="sc2" class="tabcontent">
Visit our <a href="http://www.dynamicdrive.com/new.htm">What's New</a> section to see recently added scripts to our archive.
</div>
<div id="sc3" class="tabcontent">
Visit our <a href="http://www.dynamicdrive.com/hot.htm">Hot</a> section for a list of DD scripts that are popular to the visitors.
</div>
<div id="sc4" class="tabcontent">
<form action="http://www.google.com/search" method="get" onSubmit="this.q.value='site:www.dynamicdrive.com '+this.qfront.value">
<p>Search Dynamic Drive:<br />
<input name="q" type="hidden" />
<input name="qfront" type="text" style="width: 180px" /> <input type="submit" value="Search" /></p>
</form>
</div>
</DIV>

Script Home Page

external js switcher - News menu

Download js News Box

Jump Menu Switching (jump menu content changes on Radio buttons select)

Download Drop Down Menu Switch

Right Click Menu IE5.5+

Download Right Click Context Menu Script

Featureless Window - Pop up window with custom properties

<A HREF="javascript:void(0)"
ONCLICK="window.open
('http://www.google.com','miniwin','toolbar=0,location=0,directories=0,
status=0,menubar=0,scrollbars=0,resizable=0,width=500,height=300')">
Open A Window</a>

Button Pop-Up

Head Section Code
<script language="JavaScript" type="text/JavaScript">
function openPopup(){
window.open("","_popup","toolbars=0,location=0,width=300,height=150,
toolbar=0,menubar=0,location=0,screenX=0,screenY=100,scrollbars=no,
resizable=0,statusbar=0");
return true;
}
Body Section Code
<form action="votes.php" method="post" target="_popup" onsubmit="return openPopup()"> 
<input type="submit" value="VOTE">
</form>

By this way you can also post variables to POP UP and get the results there.

Pop-Up - Body Based

From body based; I mean that you need no code to past in head section of page for this popup.

<a href="#" title="Click to view" onClick="window.open('http://www.msn.com', 'win_ranking', 'width=320,height=197,toolbar=0,menubar=0,location=0,left=0,top=113,screenX=0,screenY=100,scrollbars=no'); return false;">text or image to which you want to associae this popup</a>

Pop-Up Using Head and Body of Web page

Head Section Code
<script language="JavaScript" type="text/JavaScript">
function MM_openBrWindow(theURL,winName,features) 
{ 
window.open(theURL,winName,features);
}
Body Section Code
<a href="#" target="_self" onClick="MM_openBrWindow('javascript_all_in_one_2.htm','maintn32','')">This page Switch to full screen</a>

Pop-Up Window Maker

popup window generator

Pop-Up Box - On Load - Cross Browser

Head Section Code
<script type="text/javascript">
var ns4=document.layers
var ie4=document.all
var ns6=document.getElementById&&!document.all
//drag drop function for NS 4////
/////////////////////////////////
var dragswitch=0
var nsx
var nsy
var nstemp
function drag_dropns(name){
if (!ns4)
return
temp=eval(name)
temp.captureEvents(Event.MOUSEDOWN | Event.MOUSEUP)
temp.onmousedown=gons
temp.onmousemove=dragns
temp.onmouseup=stopns
}
function gons(e){
temp.captureEvents(Event.MOUSEMOVE)
nsx=e.x
nsy=e.y
}
function dragns(e){
if (dragswitch==1){
temp.moveBy(e.x-nsx,e.y-nsy)
return false
}
}
function stopns(){
temp.releaseEvents(Event.MOUSEMOVE)
}
//drag drop function for ie4+ and NS6////
/////////////////////////////////
function drag_drop(e){
if (ie4&&dragapproved){
crossobj.style.left=tempx+event.clientX-offsetx
crossobj.style.top=tempy+event.clientY-offsety
return false
}
else if (ns6&&dragapproved){
crossobj.style.left=tempx+e.clientX-offsetx+"px"
crossobj.style.top=tempy+e.clientY-offsety+"px"
return false
}
}
function initializedrag(e){
crossobj=ns6? document.getElementById("showimage") : document.all.showimage
var firedobj=ns6? e.target : event.srcElement
var topelement=ns6? "html" : document.compatMode && document.compatMode!="BackCompat"? "documentElement" : "body"
while (firedobj.tagName!=topelement.toUpperCase() && firedobj.id!="dragbar"){
firedobj=ns6? firedobj.parentNode : firedobj.parentElement
}
if (firedobj.id=="dragbar"){
offsetx=ie4? event.clientX : e.clientX
offsety=ie4? event.clientY : e.clientY
tempx=parseInt(crossobj.style.left)
tempy=parseInt(crossobj.style.top)
dragapproved=true
document.onmousemove=drag_drop
}
}
document.onmouseup=new Function("dragapproved=false")
////drag drop functions end here//////
function hidebox(){
crossobj=ns6? document.getElementById("showimage") : document.all.showimage
if (ie4||ns6)
crossobj.style.visibility="hidden"
else if (ns4)
document.showimage.visibility="hide"
}
</script>
Body Section Code
<div id="showimage" style="position:absolute;width:250px;left:250px;top:250px">
<table border="0" width="250" bgcolor="#000080" cellspacing="0" cellpadding="2">
<tr>
<td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0"
height="36px">
<tr>
<td id="dragbar" style="cursor:hand; cursor:pointer" width="100%" onMousedown="initializedrag(event)"><ilayer width="100%" onSelectStart="return false"><layer width="100%" onMouseover="dragswitch=1;if (ns4) drag_dropns(showimage)" onMouseout="dragswitch=0"><font face="Verdana"
color="#FFFFFF"><strong><small>Announcement Box</small></strong></font></layer></ilayer></td>
<td style="cursor:hand"><a href="#" onClick="hidebox();return false"><img src="close.gif" width="16px"
height="14px" border=0></a></td>
</tr>
<tr>
<td width="100%" bgcolor="#FFFFFF" style="padding:4px" colspan="2">
<!-- PUT YOUR CONTENT BETWEEN HERE -->
Testing 1 2 3
<!-- END YOUR CONTENT HERE -->
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>

Focus (Window Focus)

<body onblur="self.focus();">

Jump to Top Sliding Scrolling Button

Jump to top scrolling button.

Download Jump To Top Script

Javascript Essentials Part 2

In Javascript Essential Part-2 we will cover following tasks.

  • Page Fit to Screen
  • No Right Click (no alert)
  • No Right Click with alert
  • No Right Click on Images
  • Disable Image Toolbar script
  • Count Down (Live)
  • Count Up (Live) FF1+ IE5+ Opr7+
  • Scroll bar color - 16-A- Left Scroll bar
  • No Scroll bar
  • Auto Page Reloaded-Auto Refresh - Meta tag based - Button based -Live Refresh with countdown
  • Dynamically Re sized Iframe - Auto Re sizable Iframe (IE5+/NS6)
  • Switch content -Tabbed content - FF1+ IE5+ Opr7+
  • Special content switching with div
  • Switch content 2 - FF1+ IE5+

Page Fit to Screen

Add this script in the head section of page to switch the page position to fit the screen.

<script language="JavaScript">
self.moveTo(0,0)
self.resizeTo(screen.availWidth,screen.availHeight)
</script>

No Right Click (no alert)

Add this script in body tag:

oncontextmenu="return false" ondragstart="return false" onselectstart="return false"

i.e.

<body oncontextmenu="return false" ondragstart="return false" onselectstart="return false">

OR

Use the following script in body section of web page anywhere:

<script language=JavaScript>
var message="";
function clickIE() {if (document.all) {(message);return false;}}
function clickNS(e) {if 
(document.layers||(document.getElementById&&!document.all)) {
if (e.which==2||e.which==3) {(message);return false;}}}
if (document.layers) 
{document.captureEvents(Event.MOUSEDOWN);document.onmousedown=clickNS;}
else{document.onmouseup=clickNS;document.oncontextmenu=clickIE;}
document.oncontextmenu=new Function("return false")
</script>

No Right Click With Alert

simply copy the following script into body of page anywhere.

<script language="JavaScript">
var message="Sorry, that function is disabled.\nThis Page Copyrighted and\nImages and Text protected!\nALL RIGHTS RESERVED"; 
function click(e) {
if (document.all) {
if (event.button == 2) {
alert(message);
return false;
}
}
if (document.layers) {
if (e.which == 3) {
alert(message);
return false;
}
}
}
if (document.layers) {
document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown=click;
</script>

No Right Click on Images

Add the following script at the end of page right before tag.

<script language="JavaScript1.2">
var clickmessage="Right click disabled on images!"
function disableclick(e) {
if (document.all) {
if (event.button==2||event.button==3) {
if (event.srcElement.tagName=="IMG"){
alert(clickmessage);
return false;
}
}
}
else if (document.layers) {
if (e.which == 3) {
alert(clickmessage);
return false;
}
}
else if (document.getElementById){
if (e.which==3&&e.target.tagName=="IMG"){
alert(clickmessage)
return false
}
}
} function associateimages(){
for(i=0;i<document.images.length;i++)
document.images[i].onmousedown=disableclick;
}
 
if (document.all)
document.onmousedown=disableclick
else if (document.getElementById)
document.onmouseup=disableclick
else if (document.layers)
associateimages()
</script>

Disable Image Toolbar script

Use the following script in meta tags in head. It disable all images tool bars in web page document.

<META HTTP-EQUIV="imagetoolbar" CONTENT="no">

OR

Use inside the particular image(s), add the following one attribute like following:

<img src="test.gif" GALLERYIMG="no">

Count Down (Live)

<script language="JavaScript1.2"> function setcountdown(theyear,themonth,theday){
yr=theyear;mo=themonth;da=theday
}
setcountdown(2006,8,8)
var occasion="Predicted day!"
var message_on_occasion="Today was the day!"
var countdownwidth='510px'
var countdownheight='20px'
var countdownbgcolor='white'
var opentags='<font face="Verdana"><small>'
var closetags='</small></font>'
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var crosscount=''
function start_countdown(){
if (document.layers)
document.countdownnsmain.visibility="show"
else if (document.all||document.getElementById)
crosscount=document.getElementById&&!document.all?document.getElementById("countdownie") : countdownie
countdown()
}
if (document.all||document.getElementById)
document.write('<span id="countdownie" style="width:'+countdownwidth+'; background-color:'+countdownbgcolor+'"></span>')
window.onload=start_countdown
function countdown(){
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
futurestring=montharray[mo-1]+" "+da+", "+yr
dd=Date.parse(futurestring)-Date.parse(todaystring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
//if on day of occasion
if(dday<=0&&dhour<=0&&dmin<=0&&dsec<=1&&todayd==da){
if (document.layers){
document.countdownnsmain.document.countdownnssub.document.write(opentags+message_on_occasion+closetags)
document.countdownnsmain.document.countdownnssub.document.close()
}
else if (document.all||document.getElementById)
crosscount.innerHTML=opentags+message_on_occasion+closetags
return
}
//if passed day of occasion
else if (dday<=-1){
if (document.layers){
document.countdownnsmain.document.countdownnssub.document.write(opentags+"Occasion already passed! "+closetags)
document.countdownnsmain.document.countdownnssub.document.close()
}
else if (document.all||document.getElementById)
crosscount.innerHTML=opentags+"Occasion already passed! "+closetags
return
}
//else, if not yet
else{
if (document.layers){
document.countdownnsmain.document.countdownnssub.document.write(opentags+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left until "+occasion+closetags)
document.countdownnsmain.document.countdownnssub.document.close()
}
else if (document.all||document.getElementById)
crosscount.innerHTML=opentags+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds left until "+occasion+closetags
}
setTimeout("countdown()",1000)
}
</script> <ilayer id="countdownnsmain" width=&{countdownwidth}; height=&{countdownheight}; bgcolor=&{countdownbgcolor}; visibility=hide> 
<layer id="countdownnssub" width=&{countdownwidth}; height=&{countdownheight}; left=0 top=0></layer>
</ilayer>

Count Up (Live) FF1+ IE5+ Opr7+

<script language="JavaScript1.2">
function setcountup(theyear,themonth,theday){
yr=theyear;mo=themonth;da=theday
}
//////////CONFIGURE THE countup SCRIPT HERE//////////////////
//STEP 1: Configure the date to count up from, in the format year, month, day:
//This date should be less than today
setcountup(1999,3,2)
//STEP 2: Configure text to be attached to count up
var displaymessage="have passed since the debut of our site!"
//STEP 3: Configure the below 5 variables to set the width, height, background color, and text style of the countup area
var countupwidth='95%'
var countupheight='20px' //applicable only in NS4
var countupbgcolor='lightyellow'
var opentags='<font face="Verdana"><small>'
var closetags='</small></font>'
//////////DO NOT EDIT PASS THIS LINE//////////////////
var montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
var crosscount=''
function start_countup(){
if (document.layers)
document.countupnsmain.visibility="show"
else if (document.all||document.getElementById)
crosscount=document.getElementById&&!document.all?document.getElementById("countupie") : countupie
countup()
}
if (document.all||document.getElementById)
document.write('<span id="countupie" style="width:'+countupwidth+'; background-color:'+countupbgcolor+'"></span>')
window.onload=start_countup
function countup(){
var today=new Date()
var todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
var todaym=today.getMonth()
var todayd=today.getDate()
var todayh=today.getHours()
var todaymin=today.getMinutes()
var todaysec=today.getSeconds()
var todaystring=montharray[todaym]+" "+todayd+", "+todayy+" "+todayh+":"+todaymin+":"+todaysec
paststring=montharray[mo-1]+" "+da+", "+yr
dd=Date.parse(todaystring)-Date.parse(paststring)
dday=Math.floor(dd/(60*60*1000*24)*1)
dhour=Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1)
dmin=Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1)
dsec=Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1)
if (document.layers){
document.countupnsmain.document.countupnssub.document.write(opentags+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds "+displaymessage+closetags)
document.countupnsmain.document.countupnssub.document.close()
}
else if (document.all||document.getElementById)
crosscount.innerHTML=opentags+dday+ " days, "+dhour+" hours, "+dmin+" minutes, and "+dsec+" seconds "+displaymessage+closetags
setTimeout("countup()",1000)
}
</script>
<ilayer id="countupnsmain" width=&{countupwidth}; height=&{countupheight}; bgColor=&{countupbgcolor}; visibility=hide><layer id="countupnssub" width=&{countupwidth}; height=&{countupheight}; left=0 top=0></layer></ilayer>

Scroll bar color

Add the following css in your styles.css file. Change color values in following as required.

BODY{
SCROLLBAR-FACE-COLOR: #cfced2;
SCROLLBAR-HIGHLIGHT-COLOR: #f6f6f7;
SCROLLBAR-SHADOW-COLOR: #cfced2; 
SCROLLBAR-3DLIGHT-COLOR: #b3b3b3; 
SCROLLBAR-ARROW-COLOR: #4a5b86; 
SCROLLBAR-TRACK-COLOR: #e5e5e5; 
SCROLLBAR-DARKSHADOW-COLOR: #919194; 
BACKGROUND-COLOR: #ffffff
}

OR

For HTML Page Add the following in head section:

<style type="text/css">
BODY {
SCROLLBAR-FACE-COLOR: #FFA3A3;
SCROLLBAR-HIGHLIGHT-COLOR: #FFA3A3; 
SCROLLBAR-SHADOW-COLOR: #FFA3A3; 
SCROLLBAR-3DLIGHT-COLOR: #FFA3A3; 
SCROLLBAR-ARROW-COLOR: #FF7979; 
SCROLLBAR-TRACK-COLOR: #FF7979; 
SCROLLBAR-DARKSHADOW-COLOR: #000000
}
</style>

Left Scroll bar

Inside of your tag add:

style="direction:rtl"

Then, before adding any content, put this line:

<div style="direction:ltr">

i.e.

<BODY style="DIRECTION: rtl">
<DIV style="DIRECTION: ltr">

No Scroll bar

For No Scroll bar in Page, use ’scroll is equals to no’ in body tag.

<body scroll=no>

Auto Page Reloaded-Auto Refresh - Meta tag based - Button based -Live Refresh with countdown

<META HTTP-EQUIV="REFRESH" CONTENT="300">

Refresh Button

<script language="JavaScript">
document.write('<form><input type=button value="Refresh the browser with button" onClick="history.go()"></form>')
</script>

Live Refresh with countdown

<script language="JavaScript">
//configure refresh interval (in seconds)
var countDownInterval=60;
//configure width of displayed text, in px (applicable only in NS4)
var c_reloadwidth=200
</script> 
<ilayer id="c_reload" width=&{c_reloadwidth}; ><layer id="c_reload2" width=&{c_reloadwidth}; left=0 top=0></layer></ilayer>
<script>
var countDownTime=countDownInterval+1;
function countDown(){
countDownTime--;
if (countDownTime <=0){
countDownTime=countDownInterval;
clearTimeout(counter)
window.location.reload()
return
}
if (document.all) //if IE 4+
document.all.countDownText.innerText = countDownTime+" ";
else if (document.getElementById) //else if NS6+
document.getElementById("countDownText").innerHTML=countDownTime+" "
else if (document.layers){ //CHANGE TEXT BELOW TO YOUR OWN
document.c_reload.document.c_reload2.document.write('Next <a href="javascript:window.location.reload()">refresh</a> in <b id="countDownText">'+countDownTime+' </b> seconds')
document.c_reload.document.c_reload2.document.close()
}
counter=setTimeout("countDown()", 1000);
}
function startit(){
if (document.all||document.getElementById) //CHANGE TEXT BELOW TO YOUR OWN
document.write('Next <a href="javascript:window.location.reload()">refresh</a> in <b id="countDownText">'+countDownTime+' </b> seconds')
countDown()
}
if (document.all||document.getElementById)
startit()
else
window.onload=startit
</script>

Dynamically Re sized Iframe - Auto Re sizable Iframe (IE5+/NS6)

Head Section

<script type="text/javascript">
//Input the IDs of the IFRAMES you wish to dynamically resize to match its content height:
//Separate each ID with a comma. Examples: ["myframe1", "myframe2"] or ["myframe"] or [] for none:
var iframeids=["myframe"]
//Should script hide iframe from browsers that don't support this script (non IE5+/NS6+ browsers. Recommended):
var iframehide="yes"
var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers
function dyniframesize() {
var dyniframe=new Array()
for (i=0; i<iframeids.length; i++){
if (document.getElementById){ //begin resizing iframe procedure
dyniframe[dyniframe.length] = document.getElementById(iframeids[i]);
if (dyniframe[i] && !window.opera){
dyniframe[i].style.display="block"
if (dyniframe[i].contentDocument && dyniframe[i].contentDocument.body.offsetHeight) //ns6 syntax
dyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight+FFextraHeight; 
else if (dyniframe[i].Document && dyniframe[i].Document.body.scrollHeight) //ie5+ syntax
dyniframe[i].height = dyniframe[i].Document.body.scrollHeight;
}
}
//reveal iframe for lower end browsers? (see var above):
if ((document.all || document.getElementById) && iframehide=="no"){
var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i])
tempobj.style.display="block"
}
}
}
if (window.addEventListener)
window.addEventListener("load", dyniframesize, false)
else if (window.attachEvent)
window.attachEvent("onload", dyniframesize)
else
window.onload=dyniframesize
</script>

Body Section

<iframe id="myframe" src="externalpage.htm" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" style="overflow:visible; width:100%; display:none"></iframe>

Switch content -Tabbed content - FF1+ IE5+ Opr7+

http://www.dynamicdrive.com/dynamicindex17/switchcontent2.htm

Special content switching with div

Download Switching Content Menu Script

Switch content 2 - FF1+ IE5+

Head section
<script type="text/javascript">
var enablepersist="on" //Enable saving state of content structure using session cookies? (on/off)
var collapseprevious="no" //Collapse previously open content when opening present? (yes/no)
var contractsymbol='- ' //HTML for contract symbol. For image, use: <img src="whatever.gif">
var expandsymbol='+ ' //HTML for expand symbol.
if (document.getElementById){
document.write('<style type="text/css">')
document.write('.switchcontent{display:none;}')
document.write('</style>')
}
function getElementbyClass(rootobj, classname){
var temparray=new Array()
var inc=0
var rootlength=rootobj.length
for (i=0; i<rootlength; i++){
if (rootobj[i].className==classname)
temparray[inc++]=rootobj[i]
}
return temparray
}
function sweeptoggle(ec){
var thestate=(ec=="expand")? "block" : "none"
var inc=0
while (ccollect[inc]){
ccollect[inc].style.display=thestate
inc++
}
revivestatus()
}
function contractcontent(omit){
var inc=0
while (ccollect[inc]){
if (ccollect[inc].id!=omit)
ccollect[inc].style.display="none"
inc++
}
}
function expandcontent(curobj, cid){
var spantags=curobj.getElementsByTagName("SPAN")
var showstateobj=getElementbyClass(spantags, "showstate")
if (ccollect.length>0){
if (collapseprevious=="yes")
contractcontent(cid)
document.getElementById(cid).style.display=(document.getElementById(cid).style.display!="block")? "block" : "none"
if (showstateobj.length>0){ //if "showstate" span exists in header
if (collapseprevious=="no")
showstateobj[0].innerHTML=(document.getElementById(cid).style.display=="block")? contractsymbol : expandsymbol
else
revivestatus()
}
}
}
function revivecontent(){
contractcontent("omitnothing")
selectedItem=getselectedItem()
selectedComponents=selectedItem.split("|")
for (i=0; i<selectedComponents.length-1; i++)
document.getElementById(selectedComponents[i]).style.display="block"
}
function revivestatus(){
var inc=0
while (statecollect[inc]){
if (ccollect[inc].style.display=="block")
statecollect[inc].innerHTML=contractsymbol
else
statecollect[inc].innerHTML=expandsymbol
inc++
}
}
function get_cookie(Name) { 
var search = Name + "="
var returnvalue = "";
if (document.cookie.length > 0) {
offset = document.cookie.indexOf(search)
if (offset != -1) { 
offset += search.length
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
returnvalue=unescape(document.cookie.substring(offset, end))
}
}
return returnvalue;
}
function getselectedItem(){
if (get_cookie(window.location.pathname) != ""){
selectedItem=get_cookie(window.location.pathname)
return selectedItem
}
else
return ""
}
function saveswitchstate(){
var inc=0, selectedItem=""
while (ccollect[inc]){
if (ccollect[inc].style.display=="block")
selectedItem+=ccollect[inc].id+"|"
inc++
}
document.cookie=window.location.pathname+"="+selectedItem
}
function do_onload(){
uniqueidn=window.location.pathname+"firsttimeload"
var alltags=document.all? document.all : document.getElementsByTagName("*")
ccollect=getElementbyClass(alltags, "switchcontent")
statecollect=getElementbyClass(alltags, "showstate")
if (enablepersist=="on" && ccollect.length>0){
document.cookie=(get_cookie(uniqueidn)=="")? uniqueidn+"=1" : uniqueidn+"=0" 
firsttimeload=(get_cookie(uniqueidn)==1)? 1 : 0 //check if this is 1st page load
if (!firsttimeload)
revivecontent()
}
if (ccollect.length>0 && statecollect.length>0)
revivestatus()
}
if (window.addEventListener)
window.addEventListener("load", do_onload, false)
else if (window.attachEvent)
window.attachEvent("onload", do_onload)
else if (document.getElementById)
window.onload=do_onload if (enablepersist=="on" && document.getElementById)
window.onunload=saveswitchstate
</script>
Body section
<!--Optional Expand/ Contact All links. Remove if desired-->
<div><a href="javascript:sweeptoggle('contract')">Contract All</a> | <a href="javascript:sweeptoggle('expand')">Expand All</a></div>
<h3 onClick="expandcontent(this, 'sc1')" style="cursor:hand; cursor:pointer"><span class="showstate"></span>What is JavaScript?</h3>
<div id="sc1" class="switchcontent">
JavaScript is a scripting language originally developed by Netscape to add interactivity and power to web documents. It is purely client side, and runs completely on the client's browser and computer.
</div>
<h3 onClick="expandcontent(this, 'sc2')" style="cursor:hand; cursor:pointer"><span class="showstate"></span>Difference betwen Java & JavaScript?</h3>
<div id="sc2" class="switchcontent">
Java is completely different from JavaScript- the former is a compiled language while the later is a scripting language.
</div>
<h3 onClick="expandcontent(this, 'sc3')" style="cursor:hand; cursor:pointer"><span class="showstate"></span>What is DHTML?</h3>
<div id="sc3" class="switchcontent">
DHTML is the embodiment of a combination of technologies- JavaScript, CSS, and HTML. Through them a new level of interactivity is possible for the end user experience.
</div>

Example - Dynamic Drive

Javascript Essentials Part 1

This section contains following solutions to javascript.

  • Make Home Page Script (text based, image based)
  • Add to Favorites Script (Cross Browser, By Image, By text)
    (Simple, Cross Browser support, Onload add to favorites)
  • Switch to Full Screen
  • Last Date of Page Updated
  • Print Page (IE, Cross Browser)
  • Save page from printing (Printing Security Issue)
  • Website Launched Since
  • Close window
    (With Prompt, Without Prompt, Self close with time (5000 for 5 sec.) Auto close with prompt, Self close with time (3000 for 3sec.) Auto close without prompt)
  • Open window on browser close - Open window on close window
  • Back Button (history.back)
    (Text based, Image based, History back and forward buttons)

Make Home Page Script

Text Based Script
<!--[if IE]>
<A HREF="#" class="downlinks"
onClick="this.style.behavior='url(#default#homepage)';
this.setHomePage('http://www.webstylepress.com');">
Make Webstylepress Homepage
</A>
<![endif]-->
Image Based Script
<a href="#" onClick="this.style.behavior='url(#default#homepage)';this.setHomePage('http://www.webstylepress.com');"><img src="images/homepage.jpg" alt="Make WebStylePress Homepage" name="Image-HomePage" width="" height="" border="0">

Add to Favorites Cross Browser Script

Add the following In Head Section
<script type="text/javascript">
function bookmarksite(title, url){
if (document.all)
window.external.AddFavorite(url, title);
else if (window.sidebar)
window.sidebar.addPanel(title, url, "")
}
</script>

Now that you have included script in head section, lets move to body part of script.

Add the following In Body Section

You can display add to favorite link in web page based on text or image as following.

Text Based
<a href="javascript:bookmarksite('Webstylepress', 'http://www.webstylepress.com')">Bookmark this site!</a>
Image Based
<a href="#" onClick="javascript:window.external.AddFavorite('http://www.webstylepress.com', 'Webstylepress, Web developers guide');"><img src="images/bt2_1.jpg" alt=".add to favourites" name="Image4" width="34" height="34" border="0"></a>
Onload Add to favorites Script

This script will be added in body tag of web page. When web page will be completed loading, it will ask user to add website into favorites.

<body onLoad="if(document.all) window.external.AddFavorite(window.document.location,window.document.title)">

Switch to Full Screen Script

This script consists of two parts. First a part of code you have to add in head section and second piece of code you will add in body section to display link to click to for making that web page homepage of browser.

Head Section Script
<script language="JavaScript" type="text/JavaScript">
function MM_openBrWindow(theURL,winName,features) { //v2.0
window.open(theURL,winName,features);
}
</script>
Body Section Code
<a href="#" 
target="_self" class="downlinks" 
onClick="MM_openBrWindow('index1.htm','maintn32','fullscreen=yes')">Switch to full screen
</a>

index1.htm is the page which will be switched to full screen.

Last Date of Page Updated

Want to know which date the page was last modified or updated? Add following javascript code in body section of page.

<SCRIPT language=JavaScript>
var m = "" + document.lastModified;
var p = m.length-8;
document.write(m.substring(p, 0));
</SCRIPT>

Print Page Script (Cross Browser)

<SCRIPT LANGUAGE="JavaScript">
if (window.print) {
document.write('<form>'
+ '<input type=button name=print value="Print" '
+ 'onClick="javascript:window.print()"></form>');
}
</script>

OR Print Button (Cross Browser Compatible)

<SCRIPT Language="Javascript">
function printit(){ 
if (window.print) {
window.print() ; 
} else {
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(6, 2);//Use a 1 vs. a 2 for a prompting dialog box WebBrowser1.outerHTML = ""; 
}
}
</script> 
<SCRIPT Language="Javascript"> 
var NS = (navigator.appName == "Netscape");
var VERSION = parseInt(navigator.appVersion);
if (VERSION > 3) {
document.write('<form><input type=button value="Print this Page" name="Print" onClick="printit()"></form>'); 
}
</script>

OR

Print Through Image
<a href="#" onClick="javascript:window.print()">
<img src="someimage.jpg"></a>

Save Page From Printing Script (Printing Security Issue)

<link rel=alternate media=print href="printversion.doc">

Add above script into your head section of page. When user will try to print the page an alternative print will come out according to document mentioned in href (in this case printversion.doc).

Website Launched Since - Javascript Code

<script language="javascript">
montharray=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
function countup(yr,m,d){
today=new Date()
todayy=today.getYear()
if (todayy < 1000)
todayy+=1900
todaym=today.getMonth()
todayd=today.getDate()
todaystring=montharray[todaym]+" "+todayd+", "+todayy
paststring=montharray[m-1]+" "+d+", "+yr
difference=(Math.round((Date.parse(todaystring)-Date.parse(paststring))/(24*60*60*1000))*1)
difference+=" days"
document.write("It has been "+difference+" since the launch of website name")
}
//enter the count up date using the format year/month/day
countup(2005,09,07)
</script>

Close Window Script

Close Browser Window With Prompt
<a href="Javascript:self.close();" class="downlinks">Close website</a>
Without Prompt
<a href="#" 
onclick="window.opener=null; window.close(); return false">
thelinkbuttonorwhatever
</a>
Self Close With time (5000 for 5 sec.) Auto Close Browser Window With Prompt
<script language="javascript"> 
setTimeout("self.close();",5000) 
</script>
Self Close With time (3000 for 3sec.) Auto Close Without Prompt
<script language="javascript"> 
setTimeout("self.opener=null; self.close(); return false;",3000) 
</script>

Open Browser Window on Browser Window Close - Open Window on Close Window

<body onUnload="window.open('http://www.google.ca/', 'newWindow', 'scrollbars=0,resizable=0,height=300,width=400')">

When viewer will close window (containing this code in body tag), he will get another window opened after closing first one which is given as url above.

Back Button (history.back) Script

Text Link
<a href="javascript:history.back(1)" target="_parent">Go back</a>
Image Link
<a href="javascript:history.back(1)" 
target="_parent">
<img src="images/this.jpg" width="100" height="20" border="0">
</a>

OR

History Back and Forward Buttons
<form>
<input type="button" value=" back " onClick="history.go(-1)">
<input type="button" value="forward" onCLick="history.go(1)">
</form>