JavaScript is a scripting language developed by Netscape to enable Web authors to design interactive sites. Although it shares many of the features and structures of the full Java language, it was developed independently. JavaScript can interact with HTML source code, enabling Web authors to spice up their sites with dynamic content. JavaScript is endorsed by a number of software companies and is an open language that anyone can use without purchasing a license.

The intent of this page is to show some useful and dynamic JavaScript examples that I have picked up in the process of creating my own webpages. Click on the bulleted items below to view JavaScript codes and tricks.

Back to previous page with a link

Copy and paste this code into your HTML where you would like the link to appear.

<a href="javascript: history.go(-1)">Back</a>

 

Back to Top^

Close a window button

Copy and paste this code into the <body> of your HTML where you would like the button to appear.

<form>
<input type="button" value="Close Window" onClick="window.close()">
</form>

or if you want a regular text link:

<a href="javascript:window.close()">Close Window</a>

Back to Top^

Display today's date on your webpage

HEAD Section Code (Paste the HEAD Section code from above between the <HEAD> and </HEAD> tags on your page) :

<SCRIPT language="JavaScript">
<!--
function write_date()
{
var thetime=new Date();

var nday=thetime.getDay();
var nmonth=thetime.getMonth();
var ntoday=thetime.getDate();
var nyear=thetime.getYear();
var AorP=" ";

if (nday==0)
nday="Sunday";
if (nday==1)
nday="Monday";
if (nday==2)
nday="Tuesday";
if (nday==3)
nday="Wednesday";
if (nday==4)
nday="Thursday";
if (nday==5)
nday="Friday";
if (nday==6)
nday="Saturday";

nmonth+=1;

if (nyear<=99)
nyear= "19"+nyear;

if ((nyear>99) && (nyear<2000))
nyear+=1900;

document.write("Today is "+nday+", "+nmonth+"-"+ntoday+"-"+nyear);

}
//-->
</SCRIPT>


BODY Section Code (Paste the BODY Section code from above between the <BODY> and </BODY> tags on your page, exactly where you want the date to appear):

<SCRIPT language="JavaScript">
<!--
write_date();
//-->
</SCRIPT>

 

Back to Top^

Hide links in status bar

Use this script to hide the status bar message from appearing when the mouse moves over certain links (placed within the <BODY> tag):

<body onmouseover="window.status='Done';return true;">


This site uses the javascript code above. Check out the status bar when you hover over any link. The link address is hidden.

Back to Top^

Make Internal Links Scroll Smoothly

When users navigate through a long document, they are often confused or disoriented when they click a link that jumps to another location in that same document. Are they on the same page, or a different page? Should they scroll more from here?

By using the procedure below, your document internal links will scroll to their destination, allowing your users to retain an awareness of where the browser is located within the document, and how far they are from their starting point. The code has been tested and works in Mozilla, IE, and Opera [10].

Step 1:

Save the following code (procedure) as a .js file within the root directory. Save the file with the name "smoothscroll.js". Comment lines are provided for a brief understanding of the function performed:

var ss = {
fixAllLinks: function() {
// Get a list of all links in the page
var allLinks = document.getElementsByTagName('a');
// Walk through the list
for (var i=0;i<allLinks.length;i++) {
var lnk = allLinks[i];
if ((lnk.href && lnk.href.indexOf('#') != -1) &&
( (lnk.pathname == location.pathname) ||
('/'+lnk.pathname == location.pathname) ) &&
(lnk.search == location.search)) {
// If the link is internal to the page (begins in #)
// then attach the smoothScroll function as an onclick
// event handler
ss.addEvent(lnk,'click',ss.smoothScroll);
}
}
},

smoothScroll: function(e) {
// This is an event handler; get the clicked on element,
// in a cross-browser fashion
if (window.event) {
target = window.event.srcElement;
} else if (e) {
target = e.target;
} else return;

// Make sure that the target is an element, not a text node
// within an element
if (target.nodeType == 3) {
target = target.parentNode;
}

// Paranoia; check this is an A tag
if (target.nodeName.toLowerCase() != 'a') return;

// Find the <a name> tag corresponding to this href
// First strip off the hash (first character)
anchor = target.hash.substr(1);
// Now loop all A tags until we find one with that name
var allLinks = document.getElementsByTagName('a');
var destinationLink = null;
for (var i=0;i<allLinks.length;i++) {
var lnk = allLinks[i];
if (lnk.name && (lnk.name == anchor)) {
destinationLink = lnk;
break;
}
}

// If we didn't find a destination, give up and let the browser do
// its thing
if (!destinationLink) return true;

// Find the destination's position
var destx = destinationLink.offsetLeft;
var desty = destinationLink.offsetTop;
var thisNode = destinationLink;
while (thisNode.offsetParent &&
(thisNode.offsetParent != document.body)) {
thisNode = thisNode.offsetParent;
destx += thisNode.offsetLeft;
desty += thisNode.offsetTop;
}

// Stop any current scrolling
clearInterval(ss.INTERVAL);

cypos = ss.getCurrentYPos();

ss_stepsize = parseInt((desty-cypos)/ss.STEPS);
ss.INTERVAL =
setInterval('ss.scrollWindow('+ss_stepsize+','+desty+',"'+anchor+'")',10);

// And stop the actual click happening
if (window.event) {
window.event.cancelBubble = true;
window.event.returnValue = false;
}
if (e && e.preventDefault && e.stopPropagation) {
e.preventDefault();
e.stopPropagation();
}
},

scrollWindow: function(scramount,dest,anchor) {
wascypos = ss.getCurrentYPos();
isAbove = (wascypos < dest);
window.scrollTo(0,wascypos + scramount);
iscypos = ss.getCurrentYPos();
isAboveNow = (iscypos < dest);
if ((isAbove != isAboveNow) || (wascypos == iscypos)) {
// if we've just scrolled past the destination, or
// we haven't moved from the last scroll (i.e., we're at the
// bottom of the page) then scroll exactly to the link
window.scrollTo(0,dest);
// cancel the repeating timer
clearInterval(ss.INTERVAL);
// and jump to the link directly so the URL's right
location.hash = anchor;
}
},

getCurrentYPos: function() {
if (document.body && document.body.scrollTop)
return document.body.scrollTop;
if (document.documentElement && document.documentElement.scrollTop)
return document.documentElement.scrollTop;
if (window.pageYOffset)
return window.pageYOffset;
return 0;
},

addEvent: function(elm, evType, fn, useCapture) {
// addEvent and removeEvent
// cross-browser event handling for IE5+, NS6 and Mozilla
// By Scott Andrew
if (elm.addEventListener){
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent){
var r = elm.attachEvent("on"+evType, fn);
return r;
} else {
alert("Handler could not be removed");
}
}
}

ss.STEPS = 100;

ss.addEvent(window,"load",ss.fixAllLinks);

Step 2:
Place this code within the <head> section of your document. This snippet will call the function "smoothscrool.js":

<script src="smoothscroll.js" type="text/javascript"></script>

Back to Top^

Make this site your home page button

You can place a button on your site that, when clicked on, will make your site your visitor's home page. Place the following code where you would like the button to appear:

<FORM>
<INPUT TYPE="button" VALUE="Make This Site Your Home Page" onClick="this.style.behavior='url(#default#homepage)'; this.setHomePage('Page URL beginning with http:// here');">
</FORM>


Back to Top^

No right click

Protect your web page's content by disabling copying by right-clicking or using the Alt and Ctrl keys. Using the procedure below will generate an alert window.

Step 1:

Save the following code (procedure) as a .js file within the root directory. Save the file with the name "norightclick.js". Comment lines are provided for a brief understanding of the function performed:

function IE(e)
//traps right-click in IE
{
if (navigator.appName == "Microsoft Internet Explorer" && (event.button == "2" || event.button == "3"))
{ alert("Right-Click Disabled");
return false;
}
}
function NS(e)
//traps right-click in Netscape/firefox, et al
{
if (document.layers || (document.getElementById && !document.all))
{
if (e.which == "2" || e.which == "3")
{
alert("Right-Click Disabled");
return false;
}
}
}
document.onmousedown=IE;
document.onmouseup=NS;
document.oncontextmenu=new Function("return false");

Step 2:
Place this code within the <head> section of your document. This snippet will call the function "norightclick.js":

<script language="javascript" src="norightclick.js"></script>

Back to Top^

Redirect to a new page

If you need to redirect visitors to a new page, the following redirect code will enable you to do just that. Place the following code between your HEAD tags:

<SCRIPT LANGUAGE="JavaScript">
<!-- Script courtesy of http://www.ecirp.com
window.location="http://www.yourdomain.com/";
// -->
</script>


OR

This example is setup to redirect to another page in 2 seconds. When a page contains this JavaScript, it will be redirected to another page that you specify in the "window.location=". You can change the number of refresh seconds by changing the "move()',2000 to the number of seconds you'd like.

Example:
1000 = 1 second
3000 = 3 seconds

Place this code between the <head> and </head> tags :

<script language="JavaScript">
<!--Script courtesy of http://www.ecirp.com - Your Guide to Professional Web Site Design and Development
var time = null
function move() {
window.location = 'http://www.yourdomain.com'
}
//-->
</script>


Place this code in your <body> tag:

<body onload="timer=setTimeout('move()',2000)">

 

Back to Top^

Setting Form Focus

Use the Javascript function: document.form.field.focus() to give the object the focus:

<body onload="document.formname.fieldname.focus()" >

OR

<form name="form1" action="somepage.asp" method="post">
<input type="text" name="city">
<input type="submit" value="Submit">
</form>
<script language="JavaScript"> document.forms[0].city.focus(); </script>

Back to Top^

Vertical Scroller

This vertical scroller supports rich HTML, and works across all major browsers (IE4+, NS4, NS6):

Follow the comments inside to configure scroller. For the scroller's contents, be sure they all exist on ONE line, and if apostrophes are used, that they are back slashed (i.e.: "We\'ll be back"). Simply add the code below where you want the scroller to appear on your page:

<script language="javascript">

//Vertical Scroller courtesy of Ecirp.com

//ENTER CONTENT TO SCROLL BELOW.
var content='<p>Visit <a href="http://www.ecirp.com">Ecirp.com</a> for free JavaScript codes.</p>';

var boxheight=150; // BACKGROUND BOX HEIGHT IN PIXELS.
var boxwidth=150; // BACKGROUND BOX WIDTH IN PIXELS.
var boxcolor="#F2F5EC"; // BACKGROUND BOX COLOR.
var speed=50; // SPEED OF SCROLL IN MILLISECONDS (1 SECOND=1000 MILLISECONDS)..
var pixelstep=2; // PIXELS "STEPS" PER REPITITION.
var godown=false; // TOP TO BOTTOM=TRUE , BOTTOM TO TOP=FALSE

// DO NOT EDIT BEYOND THIS POINT

var outer,inner,elementheight,ref,refX,refY;
var w3c=(document.getElementById)?true:false;
var ns4=(document.layers)?true:false;
var ie4=(document.all && !w3c)?true:false;
var ie5=(document.all && w3c)?true:false;
var ns6=(w3c && navigator.appName.indexOf("Netscape")>=0)?true:false;
var txt='';
if(ns4){
txt+='<table cellpadding=0 cellspacing=0 border=0 height='+boxheight+' width='+boxwidth+'><tr><td>';
txt+='<ilayer name="ref" bgcolor="'+boxcolor+'" width='+boxwidth+' height='+boxheight+'></ilayer>';
txt+='</td></tr></table>'
txt+='<layer name="outer" bgcolor="'+boxcolor+'" visibility="hidden" width='+boxwidth+' height='+boxheight+'>';
txt+='<layer name="inner" width='+(boxwidth-4)+' height='+(boxheight-4)+' visibility="hidden" left="2" top="2" >'+content+'</layer>';
txt+='</layer>';
}else{
txt+='<div id="ref" style="position:relative; width:'+boxwidth+'; height:'+boxheight+'; background-color:'+boxcolor+';" ></div>';
txt+='<div id="outer" style="position:absolute; width:'+boxwidth+'; height:'+boxheight+'; visibility:hidden; background-color:'+boxcolor+'; overflow:hidden" >';
txt+='<div id="inner" style="position:absolute; visibility:visible; left:2px; top:2px; width:'+(boxwidth-4)+'; overflow:hidden; cursor:default;">'+content+'</div>';
txt+='</div>';
}
document.write(txt);

function getElHeight(el){
if(ns4)return (el.document.height)? el.document.height : el.clip.bottom-el.clip.top;
else if(ie4||ie5)return (el.style.height)? el.style.height : el.clientHeight;
else return (el.style.height)? parseInt(el.style.height):parseInt(el.offsetHeight);
}

function getPageLeft(el){
var x;
if(ns4)return el.pageX;
if(ie4||w3c){
x = 0;
while(el.offsetParent!=null){
x+=el.offsetLeft;
el=el.offsetParent;
}
x+=el.offsetLeft;
return x;
}}

function getPageTop(el){
var y;
if(ns4)return el.pageY;
if(ie4||w3c){
y=0;
while(el.offsetParent!=null){
y+=el.offsetTop;
el=el.offsetParent;
}
y+=el.offsetTop;
return y;
}}

function scrollbox(){
if(ns4){
inner.top+=(godown)? pixelstep: -pixelstep;
if(godown){
if(inner.top>boxheight)inner.top=-elementheight;
}else{
if(inner.top<2-elementheight)inner.top=boxheight+2;
}}else{
inner.style.top=parseInt(inner.style.top)+((godown)? pixelstep: -pixelstep)+'px';
if(godown){
if(parseInt(inner.style.top)>boxheight)inner.style.top=-elementheight+'px';
}else{
if(parseInt(inner.style.top)<2-elementheight)inner.style.top=boxheight+2+'px';
}}}

window.onresize=function(){
if(ns4)setTimeout('history.go(0)', 400);
else{
outer.style.left=getPageLeft(ref)+'px';
outer.style.top=getPageTop(ref)+'px';
}}

window.onload=function(){
outer=(ns4)?document.layers['outer']:(ie4)?document.all['outer']:document.getElementById('outer');
inner=(ns4)?outer.document.layers['inner']:(ie4)?document.all['inner']:document.getElementById('inner');
ref=(ns4)?document.layers['ref']:(ie4)?document.all['ref']:document.getElementById('ref');
elementheight=getElHeight(inner);
if(ns4){
outer.moveTo(getPageLeft(ref),getPageTop(ref));
outer.clip.width=boxwidth;
outer.clip.height=boxheight;
inner.top=(godown)? -elementheight : boxheight-2;
inner.clip.width=boxwidth-4;
inner.clip.height=elementheight;
outer.visibility="show";
inner.visibility="show";
}else{
outer.style.left=getPageLeft(ref)+'px';
outer.style.top=getPageTop(ref)+'px';
inner.style.top=((godown)? -elementheight : boxheight)+'px';
inner.style.clip='rect(0px, '+(boxwidth-4)+'px, '+(elementheight)+'px, 0px)';
outer.style.visibility="visible";
}
setInterval('scrollbox()',speed);
}
</script>

<p align="center"><font face="arial" size="-2">This free script provided by Ecirp.com</font><br>
<font face="arial, helvetica" size="-2"><a href="http://www.ecirp.com">Ecirp.com</a></font></p>

Back to Top^