You are on page 1of 110

Real's HowTo PDF version.

This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ).
For uptodate content, please refer to the Web site.
There are 4 files : Real's Java , Real's Javascript, Real's Powerbuilder and Real's VBS and Misc
Prog HowTo.
Please don't make PDF versions available on the internet (it's ok in intranet)
From the PDF, you can't run the examples and the links to other Howto's are not working.
If you feel that effort has been useful to you, perhaps you will consider giving something back?
You can make a donation through PayPal at https://www.paypal.com , make you donation to
real@rgagnon.com
Contributions via PayPal are accepted in any amount using a credit card or checking account.
(Donations of any size gladly accepted)
Real's Howto copyright notice ( real@rgagnon.com )
Redistribution and use in source and binary forms,
with or without modification, are permitted provided
that the following conditions is met:
* the source code is used in a development project
Redistributions of source code or site content
(even partially) in any publications (electronic or paper)
is forbidden without permission.
DISCLAIMER
THIS SOFTWARE IS PROVIDED BY Real Gagnon "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
Real Gagnon BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Real's HowTo@www.rgagnon.com
1 Language.........................................................................................................................................1
1.1 jslanguage.......................................................................................................................1
1.2 Have an Alert box with new line in it..................................................................................1
1.3 Print special character like copyright sign..........................................................................1
1.4 Use COOKIE to count the user access to a page..............................................................2
1.5 Change an image when clicking on it................................................................................3
1.6 Check and Uncheck a checkbox........................................................................................3
1.7 Emulate the BACK button..................................................................................................4
1.8 Have a simple onscreen clock.........................................................................................4
1.9 Open a window with no menu, toolbar or status................................................................5
1.10 ",msg,"..............................................................................................................................5
1.11 Hide a Frame...................................................................................................................6
1.12 Hide a DIV........................................................................................................................6
1.13 Highlight table row...........................................................................................................8
1.13.1 On mouseOver :......................................................................................................8
1.13.2 on onClick :.............................................................................................................9
1.14 Close a window after a timeout......................................................................................10
1.15 Emit a beep....................................................................................................................10
1.16 Play a sound..................................................................................................................11
1.17 Make a window close itself after a delay........................................................................11
1.18 Use an apostrophe (') in the window status...................................................................11
1.19 Scroll a page title for special effect................................................................................12
1.20 Convert from type X to type Y........................................................................................13
1.21 Have your own error message.......................................................................................13
1.22 Get the user language...................................................................................................14
1.23 Read a data file from the server.....................................................................................14
1.24 Insert a text file into a page............................................................................................16
1.25 Include a file into a page (Ajax style).............................................................................16
1.26 Read an HTML page from the server in a variable........................................................18
1.27 Display a page from a variable......................................................................................19
1.28 Validate an email address..............................................................................................19
1.29 Do simple animation......................................................................................................20
1.30 Detect if a window is already opened............................................................................22
1.31 Easily handle parameters in the search part of a URL..................................................23
1.32 Call javascript from HREF..............................................................................................23
1.33 Use a multidimensional array.........................................................................................24
1.34 Change hyperlink text color...........................................................................................24
1.35 Add a Watermark image to your page...........................................................................26
1.36 Trap the right mouse click..............................................................................................27
1.37 Update a parent window from a child.............................................................................29
1.38 Read a META variable...................................................................................................31
1.39 Close the browser..........................................................................................................31
1.40 Get the current page name............................................................................................31
1.41 Encode a URL................................................................................................................31
1.42 Create a rectangle.........................................................................................................32
2 howto.............................................................................................................................................33
2.1 Test if a variable exists....................................................................................................33
2.2 Resize an IFRAME based on its content.........................................................................33
2.3 Compare Strings..............................................................................................................34

2.4 Remove control characters from a string

Real's HowTo@www.rgagnon.com
2 howto
2.4 Remove control characters from a string.........................................................................35
2.5 Remove all token occurrence from a string.....................................................................35
2.6 Replace a token by another in a string............................................................................36
2.7 Use regular expressions to validate/format a string.........................................................36
3 Common expressions..................................................................................................................44
3.1 Format a number as Money.............................................................................................44
3.2 Have year on 4 digits from a Date object.........................................................................44
3.3 Validate a date.................................................................................................................45
3.4 Useful Date functions.......................................................................................................45
4 Varia...............................................................................................................................................48
4.1 jsvaria............................................................................................................................48
4.2 Open a window with the right dimension for an image....................................................48
4.3 Detect if cookies are enabled...........................................................................................48
4.4 Make a switch to another page after a delay...................................................................49
4.5 Make sure that a page is displayed in a Frame...............................................................49
4.6 Make sure that a page is not displayed in a Frame.........................................................50
4.7 Send email without CGI...................................................................................................50
4.8 Send email with attachment.............................................................................................51
4.9 Instruct the browser to bypass the Cache........................................................................52
4.10 Use a JAVASCRIPT username/password instead the browser's one...........................52
4.11 Force a reload................................................................................................................53
4.12 Detect user resolution....................................................................................................54
4.13 Trigger a submit with Enter............................................................................................54
4.14 Print the current page....................................................................................................55
4.15 Add a bookmark.............................................................................................................55
4.16 Detect plugins presence................................................................................................56
4.17 Detect missing image.....................................................................................................58
4.18 Pure javascript image....................................................................................................58
4.19 Detect if the connection is possible via a secure channel..............................................59
4.20 Search a dropdown list..................................................................................................59
4.21 Carriage return in ALT tag.............................................................................................60
4.22 Encrypt data...................................................................................................................60
4.23 Erase a page without loading another page..................................................................60
4.24 Hilite a word in a page...................................................................................................60
4.25 Start an executable........................................................................................................61
4.26 Pass data from a resultset to Javascript Array..............................................................62
4.27 Disable Browser Context Menu.....................................................................................63
4.28 Disable text selection in a page.....................................................................................63
4.29 Use Excel.......................................................................................................................64
4.30 Generate a bar chart......................................................................................................66
4.31 Generate a bar chart (with Google Chart)......................................................................67
4.32 Load an HTML page depending on the browser type....................................................68
4.33 Detect browser type.......................................................................................................69
4.33.1 Detecting if a feature is present or not..................................................................69
4.33.2 Use a conditionnal comment.................................................................................69
4.33.3 Use the browser name..........................................................................................69
4.34 Allow IE to execute javascript from a local file...............................................................70

Real's HowTo@www.rgagnon.com
4 Varia
4.35 Make IE8 behave like IE7..............................................................................................70
4.36 Detect Internet Explorer.................................................................................................71
5 NOT Internet Explorer..................................................................................................................72
5.1 Protect a page access with JAVASCRIPT only...............................................................72
5.2 Associate an Icon to Favorites (IE5)................................................................................73
5.3 Execute a javascript function by clicking on text..............................................................73
5.4 Use the new <BUTTON> tag...........................................................................................74
5.5 Protect an image..............................................................................................................74
5.6 Have fixed visible URL.....................................................................................................75
5.7 Disable IE6 image toolbar................................................................................................76
5.8 Make a link to see the source of a page..........................................................................76
5.9 Cool page transition.........................................................................................................76
5.10 Cool FORM tips.............................................................................................................77
5.11 Display tooltip in HTML..................................................................................................79
5.12 Have a scrolling display.................................................................................................80
5.13 Display a page righttoleft...........................................................................................80
5.14 Have a list with colored elements..................................................................................80
5.15 Prevent printing of a page..............................................................................................81
5.16 Validate HTML...............................................................................................................81
5.17 Fix Netscape "CSS resize bug".....................................................................................82
5.18 Do simple CSS effects...................................................................................................82
5.19 Share a stylesheet.........................................................................................................83
5.20 Control background image with CSS.............................................................................84
5.21 Forcing a FormFeed when printing a page....................................................................85
5.22 Browser bugs.................................................................................................................85
5.23 Not print the submit button.............................................................................................85
5.24 Blink text........................................................................................................................86
5.25 Have text in bold in a FORM INPUT..............................................................................86
5.26 Use an Image as table cell background.........................................................................86
5.27 Customize button look and feel......................................................................................87
5.28 Embed an image into textfield........................................................................................88
5.29 Display the file type as an image on a link.....................................................................88
5.30 Add comments to CSS...................................................................................................89
6 Form...............................................................................................................................................90
6.1 jsform.............................................................................................................................90
6.2 Cool FORM tips...............................................................................................................90
6.3 Open a page from a FORM INPUT field..........................................................................91
6.4 Use multiple submit buttons on one form.........................................................................92
6.5 Send the FORM response to another FRAME................................................................92
6.6 Initialize a SELECT "on the fly"........................................................................................93
6.7 Suggest a form value.......................................................................................................95
6.8 Restrict input to alphanumeric and uppercase.................................................................95
6.9 Prevent a FORM SUBMIT with ENTER...........................................................................96
6.10 Expand a SELECT with mouse over..............................................................................97
6.11 Prevent multiple submit..................................................................................................97
6.12 Auto tab in form fields....................................................................................................98
6.13 Restrict input to alphanumeric and uppercase...............................................................98

6.14 Disable a checkbox

Real's HowTo@www.rgagnon.com
6 Form
6.14 Disable a checkbox........................................................................................................99
6.15 Make a checkbox readonly........................................................................................100
6.16 Preload images and change them with a SELECT......................................................100
6.17 Select/Unselect text in TextArea with a MouseOver....................................................101
6.18 Turn off the "autocomplete" feature of the browser.....................................................102
6.19 Limit a textarea to a maximum length..........................................................................102
6.20 Check for "letteronly" INPUT......................................................................................103
6.21 Disable/Enable a FORM..............................................................................................103
6.22 Nice "focus" effect in a FORM field..............................................................................104

1 Language
1.1 jslanguage

1.2 Have an Alert box with new line in it


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0001.html
<SCRIPT>
alert("line1\r\nline2\r\nline3");
</SCRIPT>

This tip is also good for inserting new line into a TextArea.
"\r\n" stands for carriage Return and New line. On Netscape, only the \n may be necessary but with
Explorer, you need both. To be compatible with both always use the combination "\r\n".

1.3 Print special character like copyright sign


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0002.html
Use the escape "&#" and the character number (in decimal) with ";".
Use the escape character "\" with the octal code. The following program prints all available
characters with their decimal/octal codes
<SCRIPT>
document.write("There is no &#169; on this tip");
document.write(" and no &#174; or &#153; too <br>");
for (i=33; i<256; i++) {
document.write
("&#"+i+"
dec =" + i +"
oct =" + (i).toString(8) );
document.write("<br>");
}
</SCRIPT>

output :

document.write("There is no on this tip");


document.write(" and no or too
");
for (i=33; i");
}

To show in an alert box with accented characters, use something like this :
alert("\350 \351 \352 \353 ");

Try it here
1 Language

1.4 Use COOKIE to count the user access to a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0004.html
<BODY ONLOAD="doCookie()">
<SCRIPT>
cookieName = "Counter";
function doCookie() {
var today = new Date()
var expires = new Date()
// valid for 1 year
expires.setTime(today.getTime() + 24*365*3600000)
if (document.cookie) {
index = document.cookie.indexOf(cookieName);
}
else {
index = 1;
}
if (index == 1) {
document.cookie=cookieName+"=1; " +
" expires=" + expires.toGMTString() ;
}
else {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == 1) {
countend = document.cookie.length;
}
count = eval(document.cookie.substring(countbegin, countend)) + 1;
document.cookie=cookieName+"="+count+"; " +
" expires=" + expires.toGMTString();
}
}
function getTimes() {
count=0;
if(document.cookie) {
index = document.cookie.indexOf(cookieName);
if (index != 1) {
countbegin = (document.cookie.indexOf("=", index) + 1);
countend = document.cookie.indexOf(";", index);
if (countend == 1) {
countend = document.cookie.length;
}
count = document.cookie.substring(countbegin, countend);
}
}
return(count);
}
document.write("You have accessed this page <b>"+getTimes()+"</b> times.");
if (getTimes()==0) {
document.write("Welcome! This is your first time here");

1.4 Use COOKIE to count the user access to a page

}
</SCRIPT>

1.5 Change an image when clicking on it


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0006.html
<SCRIPT>
function change_img(source,index) {
document.images[index].src = source;
}
</SCRIPT>
<A HREF="JavaScript: change_img('../images/open.gif','thisone')">
<IMG SRC="../images/closed.gif" border="0" id="thisone"></A>

Try it here :

1.6 Check and Uncheck a checkbox


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0007.html
<SCRIPT>
function checkAll(check) {
for (i=0;i<6;i++) {
if (check) {
document.forms['thisone'].chbx[i].checked=true;
}
else {
document.forms['thisone'].chbx[i].checked=false;
}
}
}
</SCRIPT>
<FORM id="thisone">
<INPUT TYPE=checkbox NAME="chbx">
<INPUT TYPE=checkbox NAME="chbx">
<INPUT TYPE=checkbox NAME="chbx">
<INPUT TYPE=checkbox NAME="chbx">
<INPUT TYPE=checkbox NAME="chbx">
<INPUT TYPE=checkbox NAME="chbx">
<INPUT TYPE=button
NAME="btnCheck" VALUE="check All"
onClick="checkAll(true)">
<INPUT TYPE=button
NAME="btnCheck" VALUE="unCheck All"
onClick="checkAll(false)">
</FORM>

Try it :

1.5 Change an image when clicking on it

1.7 Emulate the BACK button


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0008.html
<FORM>
<INPUT TYPE="button"
NAME="back"
VALUE="BACK"
onClick="history.go(1)">
</FORM>

1.8 Have a simple onscreen clock


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0009.html
<SCRIPT>
var tick;
function stop() {
clearTimeout(tick);
}
function simpleClock() {
var ut=new Date();
var h,m,s;
var time="
";
h=ut.getHours();
m=ut.getMinutes();
s=ut.getSeconds();
if(s<=9) s="0"+s;
if(m<=9) m="0"+m;
if(h<=9) h="0"+h;
time+=h+":"+m+":"+s;
document.sclock.stime.value=time;
tick=setTimeout("simpleClock()",1000);
}
</SCRIPT>
<BODY

onLoad="simpleClock();" onUnload="stop();">

<FORM NAME="sclock">
<INPUT TYPE="text" NAME="stime" SIZE="13">
</FORM>

The following version (submitted by dhoang, thanks!) is using a SPAN instead of a FORM. Using
this technique, it is easy to insert the clock in a paragraph : clock, the look is much better than
when we were using a FORM!. The new script is
<SCRIPT>
var tick;
function stop() {
clearTimeout(tick);
}
function simpleClock() {
var ut=new Date();

1.7 Emulate the BACK button

var h,m,s;
var time="
";
h=ut.getHours();
m=ut.getMinutes();
s=ut.getSeconds();
if(s<=9) s="0"+s;
if(m<=9) m="0"+m;
if(h<=9) h="0"+h;
time+=h+":"+m+":"+s;
document.getElementById('clock').innerHTML=time;
tick=setTimeout("simpleClock()",1000);
}
</SCRIPT>
<BODY

onLoad="simpleClock();" onUnload="stop();">

<p>My clock : <span id="clock">clock</span>

1.9 Open a window with no menu, toolbar or status


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0015.html
<HTML><HEAD>
<SCRIPT Language = "JavaScript">
function simpleDialog(msg) {
features =
'toolbar=no, location=no, directories=no, status=no, menubar=no, ' +
'scrollbars=no, resizable=no, width=200, height=100'
dlg = window.open ("","Dialog",features)
dlg.document.write ("<HTML><BODY bgColor='black' text='white'>")
dlg.document.write ("<H2><CENTER>",msg,"</CENTER></H2>")
dlg.document.write ("<FORM><CENTER>")
dlg.document.write
("<INPUT type='button' value='OK' onClick = 'self.close()'>")
dlg.document.write ("</CENTER></FORM></BODY></HTML>")
dlg.document.close()
}
</SCRIPT></HEAD>
<BODY><FORM>
<INPUT type='button' value = 'test simple dialog'
onClick = 'simpleDialog("Click to close")'>
</FORM></BODY></HTML>

Try it :
") dlg.document.write ("

1.10 ",msg,"
") dlg.document.write ("
") dlg.document.write ("") dlg.document.write ("

1.9 Open a window with no menu, toolbar or status

") dlg.document.close() } Note : By default with Firefox, you cannot alter browser window status bar
using javascript. In Firefox v1.5, this can be changed via Tools/Options/Content/Enable
JavaScript/Advanced = Allow scripts to change status bar text and Hide the status bar

1.11 Hide a Frame


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0020.html
<FRAMESET ROWS="100%,*">
<FRAME NAME="mainFrame" SRC="visiblepage.html" border=0>
<FRAME NAME="scriptFrame" SRC="invisiblepage.html" border=0>
</FRAMESET>

The Frame scriptFrame is invisible.


Javascript in the scriptFrame can be referenced with "top.scriptFrame.functionname()" from the
mainFrame.
That's an easy way to hide your scripts from the user.

1.12 Hide a DIV


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0086.html
Thanks to E. Blackwood for the IE6 bugfix.

<script>
var browserType;
if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {
browserType= "gecko"
}
function hide() {
if (browserType == "gecko" )
document.poppedLayer =
eval('document.getElementById("realtooltip")');
else if (browserType == "ie")
document.poppedLayer =
eval('document.getElementById("realtooltip")');
else
document.poppedLayer =
eval('document.layers["realtooltip"]');
document.poppedLayer.style.visibility = "hidden";
}
function show() {
if (browserType == "gecko" )
document.poppedLayer =
eval('document.getElementById("realtooltip")');

1.11 Hide a Frame

else if (browserType == "ie")


document.poppedLayer =
eval('document.getElementById("realtooltip")');
else
document.poppedLayer =
eval('document.layers["realtooltip"]');
document.poppedLayer.style.visibility = "visible";
}
</script>
<form>
<input type=button onClick="hide()" value="hide">
<input type=button onClick="show()" value="show">
</form>
<div id="realtooltip" style="visibility: visible">
<big>Real's HowTo</big>
<layer></layer></div>

Try it :

Real's HowTo

The above HowTo uses visibility = "visible"/"hidden" which keeps the element in the layout but does
not show the content. To actually remove the element, you use display = "none"/"inline" to force a
realignment of the page layout.
<script>
var browserType;
if (document.layers) {browserType = "nn4"}
if (document.all) {browserType = "ie"}
if (window.navigator.userAgent.toLowerCase().match("gecko")) {
browserType= "gecko"
}
function hide2() {
if (browserType == "gecko" )
document.poppedLayer =
eval('document.getElementById("realtooltip2")');
else if (browserType == "ie")
document.poppedLayer =
eval('document.getElementById("realtooltip2")');
else
document.poppedLayer =
eval('document.layers["realtooltip2"]');
document.poppedLayer.style.display = "none";
}
function show2() {
if (browserType == "gecko" )
document.poppedLayer =
eval('document.getElementById("realtooltip2")');
else if (browserType == "ie")
document.poppedLayer =
eval('document.getElementById("realtooltip2")');
else

1.11 Hide a Frame

document.poppedLayer =
eval('document.layers["realtooltip2"]');
document.poppedLayer.style.display = "inline";
}
</script>

<form>
<input type=button onClick="hide2()" value="hide">
<input type=button onClick="show2()" value="show">
</form>
<div id="realtooltip2" style="display: inline">
<big>Real's HowTo</big>
<layer></layer></div>

Try it :

Real's HowTo
1.13 Highlight table row
Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0093.html

1.13.1 On mouseOver :
<table border=1 align=center>
<caption>Statistics</caption>
<th>Year</th>
<th>Team</th>
<tr onMouseOver="this.bgColor
onMouseOut ="this.bgColor
bgcolor="#FFFFFF">
<td align=right>1930</td>
<td align=right>Detroit</td>
</tr>
<tr onMouseOver="this.bgColor
onMouseOut ="this.bgColor
bgcolor="#FFFFFF">
<td align=right>1933</td>
<td align=right>Detroit</td>
</tr>
<tr onMouseOver="this.bgColor
onMouseOut ="this.bgColor
bgcolor="#FFFFFF">
<td align=right>1934</td>
<td align=right>Detroit</td>
</tr>
<tr onMouseOver="this.bgColor
onMouseOut ="this.bgColor
bgcolor="#FFFFFF">
<td align=right>1935</td>
<td align=right>Detroit</td>
</tr>
</table>

1.13 Highlight table row

= '#C0C0C0'"
= '#FFFFFF'"

= '#C0C0C0'"
= '#FFFFFF'"

= '#C0C0C0'"
= '#FFFFFF'"

= '#C0C0C0'"
= '#FFFFFF'"

Statistics
1930
1933
1934
1935

Detroit
Detroit
Detroit
Detroit

This technique works with TD also :


Statistics
1930
1933
1934
1935

Detroit
Detroit
Detroit
Detroit

1.13.2 on onClick :
<script>
var preEl ;
var orgBColor;
var orgTColor;
function HighLightTR(el, backColor,textColor){
if(typeof(preEl)!='undefined') {
preEl.bgColor=orgBColor;
try{ChangeTextColor(preEl,orgTColor);}catch(e){;}
}
orgBColor = el.bgColor;
orgTColor = el.style.color;
el.bgColor=backColor;
try{ChangeTextColor(el,textColor);}catch(e){;}
preEl = el;
}

function ChangeTextColor(a_obj,a_color){
for (i=0;i<a_obj.cells.length;i++)
a_obj.cells(i).style.color=a_color;
}
</script>

<table border=1 align=center>


<caption>Statistics</caption>
<th>Year</th>
<th>Team</th>
<tr onClick="HighLightTR(this,'#c9cc99','cc3333');"
<td align=right>1930</td>
<td align=right>Detroit</td>
</tr>
<tr onClick="HighLightTR(this,'#c9cc99','cc3333');"
<td align=right>1933</td>
<td align=right>Detroit</td>
</tr>
<tr onClick="HighLightTR(this,'#c9cc99','cc3333');"
<td align=right>1934</td>
<td align=right>Detroit</td>
</tr>
<tr onClick="HighLightTR(this,'#c9cc99','cc3333');"

1.13.2 on onClick :

>

>

>

>

<td align=right>1935</td>
<td align=right>Detroit</td>
</tr>
</table>

Statistics
1930
1933
1934
1935

Detroit
Detroit
Detroit
Detroit

1.14 Close a window after a timeout


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0023.html
This will open a window using the welcome.html file. The window will close itself after 5 seconds.
welcome = window.open('welcome.html');
setTimeout('welcome.close()',5000)

1.15 Emit a beep


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0024.html
The only way to make a "System Beep" with Javascript is to call the JAVA beep() function (available
in JDK1.1).
<HTML>
<SCRIPT>
function beep() {
java.awt.Toolkit.getDefaultToolkit().beep();
}
</SCRIPT>
<BODY>
<FORM><INPUT TYPE=button VALUE="Beep" onClick="beep()"></FORM>
</BODY>
</HTML>

It's ok with Netscape but IE can only access Java method in an Applet (not the Java classes
directly). The workaround is to embed the call in an Applet.
import java.awt.*;
import java.applet.*;
public class JavaBeep extends Applet{
public void oneBeep() {
Toolkit.getDefaultToolkit().beep();
}
}

1.14 Close a window after a timeout

Then in javascript
document.JavaBeep.oneBeep();

1.16 Play a sound


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0025.html
[Netscape 4]
<HTML><HEAD>
<EMBED SRC="logoff.wav"
NAME="logoff"
AUTOSTART=FALSE
MASTERSOUND
HIDDEN=true>
<SCRIPT>
function beep(){
document.logoff.play();
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE="button" VALUE="Logoff" onClick="javascript:beep();">
</FORM`>
</BODY></HTML>

1.17 Make a window close itself after a delay


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0026.html
<SCRIPT>
setTimeout("self.close()", 5000 ) // after 5 seconds
</SCRIPT>

1.18 Use an apostrophe (') in the window status


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0027.html
Simply use the escape character.
window.status='welcome to real\'s home';

1.16 Play a sound

1.19 Scroll a page title for special effect


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0103.html
<html><head><title></title>
<script>
// reveal begin to end
var i = 0;
var j = 0;
var title =
"Special EffectReal'sJavascriptHowTo@http://www.rgagnon.com/howto.html";
var titlelen = title.length;
var k;
function scrollControl() {
scrollTitle();
if(j < titlelen){
clearTimeout(k);
}
j++;
k=setTimeout("scrollControl();",5)
}
function scrollTitle() {
var s = title.substring(0 ,i);
document.title = s;
i++;
}
scrollControl();
</script>
</head><body></body></html>

Try it here.
<html><head><title></title>
<script>
// scroll end to begin
var i = 0;
var j = 0;
var title =
"Special EffectReal'sJavascriptHowTo@http://www.rgagnon.com/howto.html";
var titlelen = title.length;
var k;
function scrollControl() {
scrollTitle();
if(j < titlelen){
clearTimeout(k);
}
j++;
k=setTimeout("scrollControl();",5)
}
function scrollTitle() {
var s = title.substring((titlelen i 1),titlelen);
document.title = s;
i++;
}
scrollControl();

1.19 Scroll a page title for special effect

</script>
</head><body></body></html>

Try it here.

1.20 Convert from type X to type Y


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0029.html
A string to integer
s = "12";
i = parseInt(s, 10);
OR
i = evasl(s)
OR
i = s 0;

An integer to a string
i = 12;
s = (i).toString();
or
s = "" + i;
(hex string)
(oct string)
(bin string)

s = "0x" + (i).toString(16);
s = "0" + (i).toString(8);
s = (i).toString(2);

1.21 Have your own error message


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0030.html
<SCRIPT>
window.onerror = handleErrors; // or null to suppress error message
function handleErrors(msg, url, line)
{
var errorString = "JavaScript Error Report\n";
errorString += "Message: "+msg+"\n";
errorString += "Url: "+url+"\n";
errorString += "Line: "+line;
java.lang.System.out.println(errorString);
return true;
}
</SCRIPT>

1.20 Convert from type X to type Y

1.22 Get the user language


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0032.html
For Netscape, use navigator.language
For IEv4, it's navigator.browserLanguage or navigator.userLanguage
if (navigator.appName == 'Netscape')
var language = navigator.language;
else
var language = navigator.browserLanguage;
var code = language.substring(0,2);
document.write("<P>Language = " + code);

Right now, here what this script is saying about your browser :
Language = " + code);
An alternative technique is :
var start = navigator.userAgent.indexOf('[');
if (start > 1) {
var end = navigator.userAgent.indexOf(']');
if (end > 1) {
var language = navigator.userAgent.substring(start+1,end);
document.write("<P>Language = " + language);
}
} else document.write( "Language no info available ");
document.write( "<br>useragent : " + navigator.userAgent);

Here what this script is saying about your browser :


Language = " + language); } }else document.write( "Language no info available "); document.write( "
useragent " + navigator.userAgent);

1.23 Read a data file from the server


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0034.html
for Netcape 4
<HTML><HEAD>
<SCRIPT language = "Javascript">
var data = new Array();
var i = 0;
var datafile = window.location.href.substring(0,
window.location.href.lastIndexOf("/") + 1) +
"data.txt";
var url = new java.net.URL(datafile);
var connect = url.openConnection();

1.22 Get the user language

var input = new java.io.BufferedReader(


new java.io.InputStreamReader(
connect.getInputStream()));
var aLine = ""
while((aLine = input.readLine()) != null) {
data[i++] = aLine;
}
</SCRIPT>
<BODY>
<SCRIPT language = "Javascript">
var temp = ""
for (var j = 0; j < data.length ; j++)
temp += data[j] + "<br>";
document.write(temp);
</SCRIPT>
/BODY/HTML

The data file for demonstration


[data.txt]
one
two
three
four
five
Try it here.

For Internet Explorer


<HTML><HEAD>
<SCRIPT language = "Javascript">
objXml = new ActiveXObject("Microsoft.XMLHTTP");
// objXml = new ActiveXObject("Msxml2.XMLHTTP"); older version
var datafile = "data.txt";
objXml.open("GET", datafile, true);
objXml.onreadystatechange=function() {
if (objXml.readyState==4) {
display(objXml.responseText);
}
}
objXml.send(null);
function display(msg) {
alert(msg);
}
</SCRIPT>
<BODY></BODY>
</HTML>
Try it here.

For Netscape 6
<HTML><HEAD>

1.22 Get the user language

<SCRIPT language = "Javascript">


if (document.getElementById){
objXml = new XMLHttpRequest();
objXml.open("GET",datafile,false);
objXml.send(null);
alert(objXml.responseText;
}
</SCRIPT>
<BODY></BODY>
</HTML>

See also this related HowTo

1.24 Insert a text file into a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0102.html
<object width="300" height="300" type="text/plain" data="message.txt" border="0" >
</object>

To turn off the scrollbar :


<object width="910" height="340" type="text/plain" data="message.txt" border="0"
style="overflow: hidden;">
</object>

To insert another HTML page, you simply change the type :


<object width="300" height="300" type="text/html" data="js0100.html" border="1" >
</object>

Here how it looks :


NOTE : You can achieve the same thing with the tag IFRAME but the OBJECT tag is preferred
since OBJECT is part the HTML 4 Strict specification and IFRAME is not. However, IFRAME can be
a target (for another HREF) but OBJECT can't.
Also the BORDER parameter is not supposed to work with the OBJECT tag (but some browsers
accept it). The best practice is to use a style to turn on or off the border (ex. style="border: none;").
See also this related HowTo

1.25 Include a file into a page (Ajax style)


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0115.html
With the component Microsoft.XMLHTTP for IE and XMLHttpRequest for Mozillabased browser to
make HTTP request and fetch the response without loading a new page.
1.24 Insert a text file into a page

Suppose we have an header that we want to include in each page (header.inc)


<h1>Header included</h1>

and footer (footer.inc)


<h2>Footer included</h2>

then to use them in each page we do something like this (includedemo.html)


<HTML>
<HEAD>
<TITLE> Include Demo </TITLE>
<SCRIPT LANGUAGE="JavaScript">
// new prototype defintion
document.include = function (url) {
if ('undefined' == typeof(url)) return false;
var p,rnd;
if (document.all){
// For IE, create an ActiveX Object instance
p = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
// For mozilla, create an instance of XMLHttpRequest.
p = new XMLHttpRequest();
}
// Prevent browsers from caching the included page
// by appending a random number (optional)
rnd = Math.random().toString().substring(2);
url = url.indexOf('?')>1 ? url+': url+'?rnd='+rnd;
// Open the url and write out the response
p.open("GET",url,false);
p.send(null);
document.write( p.responseText );
}
</SCRIPT>
</HEAD>
<BODY>
<script>
document.include('header.inc');
</script>
this the body
<script>
document.include('footer.inc');
</script>
</BODY>
</HTML>

Try it here
See also this related HowTo.

1.24 Insert a text file into a page

1.26 Read an HTML page from the server in a variable


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0035.html
[N4 or better]
<HTML>
<HEAD>
<SCRIPT LANGUAGE= "JavaScript1.2">
function getPage() {
// the file to be read
pageURL = new
java.net.URL
("http://www.yourserver.com/yoyrpage.html");
// step 1, open the URL
var openConnection = pageURL.openConnection;
theConnection = openConnection()
// step 2, connect to server
var t=theConnection.connect
t()
// step 3, read the file using HTTP protocol
var getContent = theConnection.getContent
var theURLStream = getContent()
// step 4, get an handle and fetch the content length
var readStream = theURLStream.read
var gcl = theConnection.getContentLength
gcLen = gcl()
// and finally, read into a variable
theText =""
for (i = 1; i <gcLen; i++) {
theText += new java.lang.Character(readStream())
}
// for demonstration
alert(theText)
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT TYPE="button" VALUE="get page" onClick="getPage();">
</FORM>
</BODY>
</HTML>

After pressing the button, wait a few seconds while the page is read, then an Alert box containing
the page content will appear, if the Alert box is bigger (probably) than the screen, just press ENTER
to close it.
The above HowTo is for Netscape.
With IE, we can load the page in hidden frame and then get its content with
1.26 Read an HTML page from the server in a variable

var sContent = document.all(0).innerHTML;

You can save / restore the body and not the whole document by using
document.all("content").innerHTML

where you have given the body an 'id' attribute of "content".


See also this related HowTo

1.27 Display a page from a variable


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0038.html
function displayHtmlFromVar(target, content) {
/*
**
target
the Html target where the page is to be displayed
**
content the page content
*/
target.close();
target.open("text/html");
target.write(content);
target.close();
}

1.28 Validate an email address


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0045.html
It's impossible to check if an address is REALLY valid but we can check for the presence of the "@"
character.
<HTML><HEAD>
<SCRIPT>
function validate_email() {
if(1 == document.jsform.email.value.indexOf("@")) {
document.jsform.email.focus();
alert("Your email must have a '@'.");
return false;
}
if(1 != document.jsform.email.value.indexOf(",")) {
document.jsform.email.focus();
alert("Your email must not have a ',' in it");
return false;
}
if(1 != document.jsform.email.value.indexOf("#")) {
document.jsform.email.focus();
alert("Your email must not have an '#' in it." );
return false;
}
if(1 != document.jsform.email.value.indexOf("!")) {
document.jsform.email.focus();

1.27 Display a page from a variable

alert("Your email must not have a '!' in it." );


return false;
}
if(1 != document.jsform.email.value.indexOf(" ")) {
document.jsform.email.focus();
alert("Your email must not have a space in it." );
return false;
}
if(document.jsform.email.value.length ==
(document.jsform.email.value.indexOf("@")+1) ) {
document.jsform.email.focus();
alert("Your email must have a domain name after the '@'.");
return false;
}
if(document.jsform.email.value.length == 0) {
document.jsform.email.focus();
alert("Please enter your email.");
return false;
}
return true;
}
</SCRIPT><BODY>
Press ENTER to validate this email address
<FORM NAME="jsform"
ONSUBMIT="return validate_email()">
<INPUT NAME="email"
TYPE="text"
SIZE="50">
</FORM></BODY></HTML>

Alternate way using regular expression:


function checkemail(str){
var filter=/^.+@.+\..{2,3}$/
return (filter.test(str))
}
While you can't validate that an email address is a real one, you can check if the domain name is real. You will find a tool to do that at this site.

1.29 Do simple animation


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0047.html
<HTML><HEAD>
<SCRIPT>
var img0 = new Image( 250, 50 );
img0.src = "../images/jht.gif";
var img1 = new Image( 250, 50 );
img1.src = "../images/jsht.gif";
var img2 = new Image( 250, 50 );
img2.src = "../images/pht.gif";
var i = 0;
var nbImg = 3; // change to the number of different images you have

1.29 Do simple animation

function animate() {
document.images[0].src = eval("img" + i ).src;
i++;
if (i == nbImg) i=0;
junk = setTimeout("animate();", 500); // in milliseconds
}
</SCRIPT>
</HEAD><BODY onLoad="animate();">
<IMG src="" width=250 height=50>
</BODY></HTML>
Try it here.

To change an image when clicking on it :


<HTML><HEAD>
<SCRIPT>
var img0 = new Image( 250, 50 );
img0.src = "../images/jht.gif";
var img1 = new Image( 250, 50 );
img1.src = "../images/jsht.gif";
var img2 = new Image( 250, 50 );
img2.src = "../images/pht.gif";
var i = 1;
var nbImg = 3; // change to the number of different images you have
function animate() {
document.images[0].src = eval("img" + i ).src;
i++;
if (i == nbImg) i=0;
}
</SCRIPT>
</HEAD><BODY>
<a href="javascript:animate();">
<IMG src="../images/jht.gif" width=250 height=50
ALT="Click to change image"></A>
/BODY/HTML
Try it here.

Changing an image when moving the mouse on it :


<HTML><HEAD>
<SCRIPT>
var img0 = new Image( 250, 50 );
img0.src = "../images/jht.gif";
var img1 = new Image( 250, 50 );
img1.src = "../images/jsht.gif";
</SCRIPT>
</HEAD><BODY>
<a href=""
onMouseOver="document.images[0].src = img1.src;"
onMouseOut="document.images[0].src = img0.src;">
<IMG src="../images/jht.gif" width=250 height=50
ALT="Move the mouse over to change image"></A>
/BODY/HTML
Try it here.

1.29 Do simple animation

Finally control the animation with buttons.


<HTML><HEAD>
<SCRIPT>
var img0 = new Image( 250, 50 );
img0.src = "../images/jht.gif";
var img1 = new Image( 250, 50 );
img1.src = "../images/jsht.gif";
var img2 = new Image( 250, 50 );
img2.src = "../images/pht.gif";

var i = 0;
var animation = true;
var nbImg = 3; // change to the number of different images you have
function animate() {
if (animation) {
document.images[0].src = eval("img" + i ).src;
}
i++;
if (i == nbImg) i=0;
junk = setTimeout("animate();", 500); // in milliseconds
}
</SCRIPT>
</HEAD><BODY onLoad="animate();">

<form>
<input type=button onClick="animation = true;" value="Start">
<input type=button onClick="animation = false;" value="Stop">
</form>

<IMG src="" width=250 height=50>


</BODY></HTML>
Try it here.

1.30 Detect if a window is already opened


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0049.html
<HTML><HEAD><SCRIPT>
var myPage;
function openMyPage() {
if (!myPage || myPage.closed){
myPage =
window.open("myPage.html", "_blank");
}
else {
alert("MyPage.html is already opened");
}
}
</SCRIPT></HEAD>
<BODY>
<FORM>
<INPUT TYPE="button"

1.30 Detect if a window is already opened

onClick="openMyPage();"
VALUE="open MyPage">
</FORM></BODY></HTML>

1.31 Easily handle parameters in the search part of a URL


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0050.html
You can extract the parameters into an array
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
TheParameters = document.location.search.substring(1,255)
alert(TheParameters)
TheParametersArray = TheParameters.split("&")
k = TheParametersArray.length
for (i= 0 ; i < k; i++) {
alert(unescape(TheParametersArray[i]))
}
</SCRIPT></BODY></HTML>

or use a regular expression


<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getParameter(p) {
// returns NULL if the parameter p is not found
var re = new RegExp('&'+p+'=([^
// for testing,
//
replace with window.location.search in real life!
var c = '?apple=steve
return (c=c.replace(/^\?/,'&').match(re)) ?c=c[1] :c='NULL';
};
// Testing:
alert(getParameter('pc'));
alert(getParameter('qqq'));
alert(getParameter('aPPLE'));
alert(getParameter('A'));
</SCRIPT></BODY></HTML>

1.32 Call javascript from HREF


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0051.html
Method 1
If Javascript is disabled then an error is displayed...

<A HREF="javascript:myFunction()">
Click here for Javascript action!</A>

1.31 Easily handle parameters in the search part of a URL

Method 2
If Javascript is disabled then a special page is displayed to warn the user...

<A HREF="nojavascripthere.html"
onClick="myFunction(); return false">
Click here for Javascript action!
</A>

1.33 Use a multidimensional array


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0054.html
// create 5x5 two dimensional array
var multidimension = new Array(5);
for ( var i=0; i < multidimension.length; i++ )
multidimension[i] = new Array(5);
// access first element
multidimension[0][0] = "hello world"

1.34 Change hyperlink text color


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0055.html
You can use the stylesheet if available.
<A HREF="../examples/blank.html"
onMouseOver="if (document.styleSheets) this.style.fontWeight='bold';"
onMouseOut="if (document.styleSheets) this.style.fontWeight='normal';">
Move over me!</A><BR>

Move over me!


NOTE : Works on IE4+

Here another solution proposed by David M. Larson (IE and Netscape)


<! Javascript/DHTML functions to implement links that
change color and size when the mouse moves over them.
This code works in both Netscape 4+ and IE 4+.
Debugged and modified by David M. Larson 07/26/2000
dml@prontomail.com >
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT language="JavaScript"> <!
var dhtml = 'NO', no = 0, enlarge_font = 1;
if (document.layers)
dhtml = 'NN'; // Netscape 4+ feature detected
if (document.all)
dhtml = 'IE'; // IE 4+ feature detected

1.33 Use a multidimensional array

function mover(object) {
if (dhtml == 'IE') {
eval(object + '.style.color = "orange"');
if (enlarge_font==1)
eval(object + '.style.fontSize = "110%"');
}
else if (dhtml == 'NN') {
eval('document.layers["' + object +
'b"].moveBelow(document.layers["' + object + 'a"])');
eval('document.layers["' + object + 'b"].visibility="hide"');
eval('document.layers["' + object + 'a"].visibility="show"');
}
}
function mout(object) {
if (dhtml == 'IE') {
eval(object + '.style.color = "blue"');
eval(object + '.style.fontSize = "100%"');
}
else if (dhtml == 'NN') {
eval('document.layers["' + object +
'a"].moveBelow(document.layers["' + object + 'b"])');
eval('document.layers["' + object + 'a"].visibility="hide"');
eval('document.layers["' + object + 'b"].visibility="show"');
}
}
function dLink(href,text) {
if (dhtml == 'IE') {
document.write('<A HREF="'+href);
document.write('" onMouseOut="mout(\'link'+no);
document.write('\')" onMouseOver="mover(\'link');
document.write(no+'\')" ID="link'+no+'">'+text);
document.write('<\/A>');
}
else if (dhtml == 'NN') {
document.write('<LAYER NAME="link'+no);
document.write('a" VISIBILITY="hide"><A HREF="');
document.write(href);
document.write('" onMouseOut="mout(\'link'+no);
document.write('\')" CLASS="different">'+text);
document.write('<\/A><\/LAYER><LAYER NAME="link');
document.write(no+'b"><A HREF="'+href);
document.write('" onMouseOver="mover(\'link'+no);
document.write('\')" CLASS="normal">'+text);
document.write('<\/A><\/LAYER>');
}
else {
document.write('<A HREF="'+href);
document.write('">'+text+'<\/A>');
}
no+=1;
}
//>
</SCRIPT>
<STYLE TYPE="text/javascript"><!
classes.different.A.color = "orange";
if (enlarge_font == 1)
classes.different.A.fontSize = "110%";

1.33 Use a multidimensional array

classes.normal.A.color = "blue";
//></STYLE>
<SCRIPT>
dLink('who.html','Dynamic Generic HTML');
document.write('<BR>');
dLink('what.html','Another Dynamic Generic HTML');
document.write('<BR>');
dLink('where.html','Yet Another');
document.write('<BR>');
dLink('when.htm','The Last');
document.write('<BR>');
document.write('<BR>');
</SCRIPT>
</BODY>
/HTML
Try it here.

1.35 Add a Watermark image to your page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0060.html
First, you need an image to use as the watermark :
Then, this "js" script file (called it "watermark.js") need to be included in your page.
// you must keep the following lines on when you use this
// original idea from the Geocities Watermark
// Nicolas http://www.javascriptpage.com
// customize this!
var window_says = "Useful code snippets for Java, JS or PB developers!";
var image_width = 20;
var image_height = 20;
var left_from_corner = 0;
var up_from_corner = 0;
var JH = 0;
var JW = 0;
var JX = 0;
var JY = 0;
var left = image_width + left_from_corner + 17;
var up = image_height + up_from_corner + 15;
if(navigator.appName == "Netscape") {
var wm = document.jsbrand;
}
if (navigator.appVersion.indexOf("MSIE") != 1){
var wm = document.all.jsbrand;
}
wm.onmouseover = msover
wm.onmouseout = msout
function watermark() {
if(navigator.appName == "Netscape") {
JH = window.innerHeight
JW = window.innerWidth

1.35 Add a Watermark image to your page

JX = window.pageXOffset
JY = window.pageYOffset
wm.visibility = "hide"
wm.top = (JH+JYup)
wm.left = (JW+JXleft)
wm.visibility= "show"
}
if (navigator.appVersion.indexOf("MSIE") != 1){
if (navigator.appVersion.indexOf("Mac") == 1){
wm.style.display = "none";
JH = document.body.clientHeight;
JW = document.body.clientWidth;
JX = document.body.scrollLeft;
JY = document.body.scrollTop;
wm.style.top = (JH+JYup);
wm.style.left =(JW+JXleft);
wm.style.display = "";
}
}
}
function msover(){
window.status = window_says
return true;
}
function msout(){
window.status = ""
return true;
}
setInterval("watermark()",100);

Then in your page add the following lines in the HTML HEAD part:
<HEAD>
...
<DIV CLASS="jsbrand" ID="jsbrand"
STYLE="position:absolute;top:1;visibility:hide;" zIndex="1000"
ALIGN="right">
<A HREF="http://tactika.com/realhome (customize this)!"
TARGET="_top"><IMG SRC="../images/realhowto.gif (customize this)"
ALT="Jump to Real's Howto Main page (customize this)" BORDER="0"></A>
</DIV>
...
</HEAD>

And finally include the watermark.js file in your page :


<SCRIPT LANGUAGE="Javascript1.2" SRC="watermark.js"></SCRIPT>
NOTE: WORKS OK WITH IE4 OR NETSCAPE4

1.36 Trap the right mouse click


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0061.html

1.36 Trap the right mouse click

<HTML><HEAD>
<script language="javascript">
function click(e) {
if (navigator.appName == 'Netscape'
&e.which == 3) {
alert("no right click please")
return false;
}
else {
if (navigator.appName == 'Microsoft Internet Explorer'
&event.button==2)
alert("no right click please")
return false;
}
return true;
}
document.onmousedown=click
</script>
</HEAD>
<BODY>
No right mouse button here!
</BODY></HTML>

Here a way posted by A. Weslowski on the Real Howto mailng list.


<HEAD>
<SCRIPT LANGUAGE="JavaScript1.2">
var ns = (document.layers)? true:false;
var ie = (document.all)? true:false;
if (ns) document.captureEvents(Event.MOUSEDOWN || Event.CLICK);
document.onclick = sourcecodeprotect;
document.onmousedown = sourcecodeprotect;
// ***********************************************************
function sourcecodeprotect(e) {
if (nsreturn false;
else if (ieutton==2)) alert("Source code protected");
else return true;
}
//***********************************************************
function cleanup() {
if (ns) document.releaseEvents(Event.MOUSEDOWN || Event.CLICK);
}
</SCRIPT>
</HEAD>
<BODY onunload="cleanup()">
No right click here!
</BODY>
NOTE: You can still see the page source via the browser menu but you can make it a little harder by opening a new window without the menu
bar or use a Frameset to display your page PLUS the above snippets to trap the RMB.

Some browsers may support a special parameter in the BODY tag to disable the RMB
<BODY oncontextmenu="return false">

To disable the Disable Mouse Dragging (Highlighting)


<BODY ondragstart="return false">

1.36 Trap the right mouse click

To disable the SELECT/COPY


<BODY onselectstart="return false">

1.37 Update a parent window from a child


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0066.html
In this example we open a child window, type a value in the field and transfer the content to parent
field.
[examplejs1.html]
<HTML><HEAD></HEAD>
<SCRIPT LANGUAGE="JavaScript">
function openChild(file,window) {
childWindow=open(file,window,'resizable=no,width=200,height=400');
if (childWindow.opener == null) childWindow.opener = self;
}
</SCRIPT>
<BODY>
<FORM NAME="parentForm">
<INPUT TYPE="button" VALUE="Open child"
onClick="openChild('examplejs2.html','win2')">
<BR><INPUT NAME="pf1" TYPE="TEXT" VALUE="">
<BR><INPUT NAME="pf2" TYPE="TEXT" VALUE="">
</FORM>
</BODY></HTML>

[examplejs2.html]
<HTML><HEAD>
<SCRIPT LANGUAGE="JavaScript">
function updateParent() {
opener.document.parentForm.pf1.value = document.childForm.cf1.value;
opener.document.parentForm.pf2.value = document.childForm.cf2.value;
self.close();
return false;
}
</SCRIPT>
</HEAD><BODY>
<FORM NAME="childForm" onSubmit="return updateParent();">
<BR><INPUT NAME="cf1" TYPE="TEXT" VALUE="">
<BR><INPUT NAME="cf2" TYPE="TEXT" VALUE="">
<BR><INPUT TYPE="SUBMIT" VALUE="Update parent">
</FORM>
</BODY></HTML>
You can try it here.

The next example updates an array with the values from a child window.
[examplejs3.html]
<HTML><HEAD></HEAD>

1.37 Update a parent window from a child

<SCRIPT LANGUAGE="JavaScript">
var myarray = new

Array ( "foo", "bar" );

function openChild(file,window) {
childWindow=open(file,window,'resizable=no,width=200,height=400');
if (childWindow.opener == null) childWindow.opener = self;
}
function showarray() {
alert(myarray.join(" | "));
}
function updatemyarray(array) {
// convert both arrays as string with a know delimiter
newarray_temp = myarray.join("|") + "|" + array.join("|")
// get a resulting array
myarray = newarray_temp.split("|");
}
</SCRIPT>
<BODY>
<INPUT TYPE="button" VALUE="Open child" onClick="openChild

('examplejs4.html','win2')">

<INPUT TYPE="button" VALUE="Show myarray content" onClick="showarray()">


</BODY></HTML>

[examplejs4.html]
<HTML><HEAD>
<SCRIPT LANGUAGE="JavaScript">
var myarray_child = new Array ( "hello" , "world" );
function showarray() {
alert(myarray_child.join(" | "));
}

function updateParentArray() {
opener.updatemyarray(myarray_child);
self.close();
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT TYPE="SUBMIT" VALUE="Update parent array" onClick="updateParentArray()">
<INPUT TYPE="button" VALUE="Show myarray_child content" onClick="showarray()">
</BODY>
</HTML>
You can try it here.

1.37 Update a parent window from a child

1.38 Read a META variable


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0070.html
<META NAME="Real's HowTo" CONTENT="http://www.rgagnon.com/">
<TITLE>Real's Javascript Howto</TITLE>
<SCRIPT>
function checkMeta() {
var metas = document.getElementsByTagName('META');
var i;
for (i = 0; i < metas.length; i++)
if (metas[i].getAttribute('NAME') == "Real's HowTo")
break;
var TestVar = metas[i].getAttribute('CONTENT');
alert(TestVar);
}
checkMeta();
</SCRIPT>

1.39 Close the browser


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0079.html
To close the browser without any warning :
<form>
<input type=button onClick='window.opener=self;window.close()' value='Close'>
</form>

WARNING, clicking on this button may close your browser!

1.40 Get the current page name


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0085.html
var sPath = window.location.pathname;
//var sPage = sPath.substring(sPath.lastIndexOf('\\') + 1);
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
alert(sPage);

1.41 Encode a URL


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0096.html
escape() encodes most of the stuff you need to encode. It misses single and double quotes, so you
should replace those manually.

1.38 Read a META variable

function URLencode(sStr) {
return escape(sStr)
.replace(/\+/g, '%2B')
.replace(/\"/g,'%22')
.replace(/\'/g, '%27');
}

Encode the following URL : www.google.com/search?q=Real's HowTo

1.42 Create a rectangle


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0108.html
<input type="button" onClick="doit()" value="Do it">
<script>
function doit() {
drawRectangle(100, 150, 200, 100);
myrect = document.getElementById("newdiv");
myrect.innerHTML= myrect.innerHTML + "<h1>howto</h1>";
}
function drawRectangle(left, top, width, height) {
if (document.createElement) {
newdiv=document.createElement("div");
newdiv.style.position="absolute";
newdiv.style.left = left+"px";
newdiv.style.top = top+"px";
newdiv.style.width = width+"px";
newdiv.style.height = height+"px";
newdiv.style.backgroundColor = 'red';
newdiv.style.visibility = 'visible';
newdiv.id = 'newdiv';
newdiv.innerHTML = "real";
document.body.appendChild(newdiv);
}
}
/SCRIPT

It looks like this

1.42 Create a rectangle

2 howto
"; } function drawRectangle(left, top, width, height) { if (document.createElement) {
newdiv=document.createElement("div"); newdiv.style.position="absolute"; newdiv.style.left =
left+"px"; newdiv.style.top = top+"px"; newdiv.style.width = width+"px"; newdiv.style.height =
height+"px"; newdiv.style.backgroundColor = 'red'; newdiv.style.visibility = 'visible'; newdiv.id =
'newdiv'; newdiv.innerHTML = "real"; document.body.appendChild(newdiv); } }

2.1 Test if a variable exists


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0112.html
var foo = "bar";
if ( typeof( window[ 'foo' ] ) != "undefined" ) {
document.write("foo is defined")
}
else {
document.write("foo is undefined")
}

Here is the result for "foo" :


And for fubar :

2.2 Resize an IFRAME based on its content


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0130.html
<script>
function calcIframeHeight() {
var the_height=
document.getElementById('iframecontent').contentWindow.
document.body.scrollHeight;
document.getElementById('iframecontent').height=
the_height;
}
function go(page) {
document.getElementById('iframecontent').src=page;
}
</script>
...
<span onClick="go('topics/javalanguage.html')">Language</span><br>
<iframe src="welcome.html"
name="iframecontent" id="iframecontent" width="100%" height="100%"

2 howto

scrolling="NO" frameborder="0"
onLoad="calcIframeHeight();window.scroll(0,0);">
</iframe>

The IFRAME onload event triggers a called to our javascript to resize the IFRAME.
But this is not working with IE8, the resize failed when loading a new document. It looks that there is
a problem with the onload event when used in the HTML tag directly
Here an alternative technique (IE8 friendly) where we attach with javascript the required function to
the IFRAME load event.

<script>
function calcIframeHeight() {
var the_height=
document.getElementById('iframecontent').contentWindow.
document.body.scrollHeight;
document.getElementById('iframecontent').height=
the_height;
}

function onloadfunction(){
// register handler for iframe load event
if (document.getElementById("iframecontent").attachEvent)
document.getElementById("iframecontent").attachEvent("onload", calcIframeHeight); // ie
else if (document.getElementById("iframecontent").addEventListener)
document.getElementById("iframecontent").addEventListener("load", calcIframeHeight, true);
}
if (window.addEventListener)
window.addEventListener("load", onloadfunction, false)
else if (window.attachEvent)
window.attachEvent("onload", onloadfunction)
else if (document.getElementById)
window.onload=onloadfunction
</script>
...
<BODY>
...
<iframe src="welcome.html"
name="iframecontent" id="iframecontent" width="100%" height="100%"
scrolling="NO" frameborder="0"
onLoad="calcIframeHeight();window.scroll(0,0);"
>
</iframe>

2.3 Compare Strings


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0017.html
Case sensitive:
if (aString == anotherString) {

2.3 Compare Strings

alert("equals");
}

Not casesensitve:
if (aString.toUpperCase() == anotherString.toUpperCase()) {
alert("equals");
}

2.4 Remove control characters from a string


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0041.html
function removeNL(s) {
/*
** Remove NewLine, CarriageReturn and Tab characters from a String
**
s string to be processed
** returns new string
*/
r = "";
for (i=0; i < s.length; i++) {
if (s.charAt(i) != '\n' &
s.charAt(i) != '\r' &
s.charAt(i) != '\t') {
r += s.charAt(i);
}
}
return r;
}

Same thing but using a regular expression


function removeNL(s){
return s.replace(/[\n\r\t]/g,);
}

Submitted by R.A. Orr

2.5 Remove all token occurrence from a string


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0042.html
function remove(s, t) {
/*
** Remove all occurrences of a token in a string
**
s string to be processed
**
t token to be removed
** returns new string
*/
i = s.indexOf(t);
r = "";
if (i == 1) return s;
r += s.substring(0,i) + remove(s.substring(i + t.length), t);

2.4 Remove control characters from a string

return r;
}

2.6 Replace a token by another in a string


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0043.html
function replace(s, t, u) {
/*
** Replace a token in a string
**
s string to be processed
**
t token to be found and removed
**
u token to be inserted
** returns new String
*/
i = s.indexOf(t);
r = "";
if (i == 1) return s;
r += s.substring(0,i) + u;
if ( i + t.length < s.length)
r += replace(s.substring(i + t.length, s.length), t, u);
return r;
}

2.7 Use regular expressions to validate/format a string


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0063.html
This is an impressive collection (that I found somehere on the Net) of various functions to validate or
format string in Javascript. The code is very compact.
/****************************************************************
FILE: RegExpValidate.js
DESCRIPTION: This file contains a library of validation functions
using javascript regular expressions. Library also contains
functions that reformat fields for display or for storage.

VALIDATION FUNCTIONS:
validateEmail checks format of email address
validateUSPhone checks format of US phone number
validateNumeric checks for valid numeric value
validateInteger checks for valid integer value
validateNotEmpty checks for blank form field
validateUSZip checks for valid US zip code
validateUSDate checks for valid date in US format
validateValue checks a string against supplied pattern
FORMAT FUNCTIONS:
rightTrim removes trailing spaces from a string
leftTrim removes leading spaces from a string

2.6 Replace a token by another in a string

trimAll removes leading and trailing spaces from a string


removeCurrency removes currency formatting characters (), $
addCurrency inserts currency formatting characters
removeCommas removes comma separators from a number
addCommas adds comma separators to a number
removeCharacters removes characters from a string that match
passed pattern

AUTHOR: Karen Gayda


DATE: 03/24/2000
*******************************************************************/
function validateEmail( strValue) {
/************************************************
DESCRIPTION: Validates that a string contains a
valid email pattern.
PARAMETERS:
strValue String to be tested for validity
RETURNS:
True if valid, otherwise false.
REMARKS: Accounts for email with country appended
does not validate that email contains valid URL
type (.com, .gov, etc.) or valid country suffix.
*************************************************/
var objRegExp =
/(^[az]([az_\.]*)@([az_\.]*)([.][az]{3})$)|(^[az]([az_\.]*)@
([az_\.]*)(\.[az]{3})(\.[az]{2})*$)/i;
//check for valid email
return objRegExp.test(strValue);
}
function validateUSPhone( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains valid
US phone pattern.
Ex. (999) 9999999 or (999)9999999
PARAMETERS:
strValue String to be tested for validity
RETURNS:
True if valid, otherwise false.
*************************************************/
var objRegExp = /^\([19]\d{2}\)\s?\d{3}\\d{4}$/;
//check for valid us phone with or without space between
//area code
return objRegExp.test(strValue);
}
function validateNumeric( strValue ) {
/*****************************************************************
DESCRIPTION: Validates that a string contains only valid numbers.
PARAMETERS:
strValue String to be tested for validity

2.6 Replace a token by another in a string

RETURNS:
True if valid, otherwise false.
******************************************************************/
var objRegExp = /(^?\d\d*\.\d*$)|(^?\d\d*$)|(^?\.\d\d*$)/;
//check for numeric characters
return objRegExp.test(strValue);
}
function validateInteger( strValue ) {
/************************************************
DESCRIPTION: Validates that a string contains only
valid integer number.
PARAMETERS:
strValue String to be tested for validity
RETURNS:
True if valid, otherwise false.
**************************************************/
var objRegExp = /(^?\d\d*$)/;
//check for integer characters
return objRegExp.test(strValue);
}
function validateNotEmpty( strValue ) {
/************************************************
DESCRIPTION: Validates that a string is not all
blank (whitespace) characters.
PARAMETERS:
strValue String to be tested for validity
RETURNS:
True if valid, otherwise false.
*************************************************/
var strTemp = strValue;
strTemp = trimAll(strTemp);
if(strTemp.length > 0){
return true;
}
return false;
}
function validateUSZip( strValue ) {
/************************************************
DESCRIPTION: Validates that a string a United
States zip code in 5 digit format or zip+4
format. 99999 or 999999999
PARAMETERS:
strValue String to be tested for validity
RETURNS:
True if valid, otherwise false.
*************************************************/
var objRegExp = /(^\d{5}$)|(^\d{5}\d{4}$)/;
//check for valid US Zipcode
return objRegExp.test(strValue);
}

2.6 Replace a token by another in a string

function validateUSDate( strValue ) {


/************************************************
DESCRIPTION: Validates that a string contains only
valid dates with 2 digit month, 2 digit day,
4 digit year. Date separator can be ., , or /.
Uses combination of regular expressions and
string parsing to validate date.
Ex. mm/dd/yyyy or mmddyyyy or mm.dd.yyyy
PARAMETERS:
strValue String to be tested for validity
RETURNS:
True if valid, otherwise false.
REMARKS:
Avoids some of the limitations of the Date.parse()
method such as the date separator character.
*************************************************/
var objRegExp = /^\d{1,2}(\|\/|\.)\d{1,2}\1\d{4}$/
//check to see if in correct format
if(!objRegExp.test(strValue))
return false; //doesn't match pattern, bad date
else{
var strSeparator = strValue.substring(2,3)
var arrayDate = strValue.split(strSeparator);
//create a lookup for months not equal to Feb.
var arrayLookup = { '01' : 31,'03' : 31,
'04' : 30,'05' : 31,
'06' : 30,'07' : 31,
'08' : 31,'09' : 30,
'10' : 31,'11' : 30,'12' : 31}
var intDay = parseInt(arrayDate[1],10);
//check if month value and day value agree
if(arrayLookup[arrayDate[0]] != null) {
if(intDay <= arrayLookup[arrayDate[0]] &intDay != 0)
return true; //found in lookup table, good date
}
//check for February (bugfix 20050322)
//bugfix for parseInt kevin
//bugfix biss year O.Jp Voutat
var intMonth = parseInt(arrayDate[0],10);
if (intMonth == 2) {
var intYear = parseInt(arrayDate[2]);
if (intDay > 0 &intDay < 29) {
return true;
}
else if (intDay == 29) {
if ((intYear % 4 == 0) &(intYear % 100 != 0) ||
(intYear % 400 == 0)) {
// year div by 4 and ((not div by 100) or div by 400) >ok
return true;
}
}
}
}
return false; //any other values, bad date
}

2.6 Replace a token by another in a string

function validateValue( strValue, strMatchPattern ) {


/************************************************
DESCRIPTION: Validates that a string a matches
a valid regular expression value.
PARAMETERS:
strValue String to be tested for validity
strMatchPattern String containing a valid
regular expression match pattern.
RETURNS:
True if valid, otherwise false.
*************************************************/
var objRegExp = new RegExp( strMatchPattern);
//check if string matches pattern
return objRegExp.test(strValue);
}

function rightTrim( strValue ) {


/************************************************
DESCRIPTION: Trims trailing whitespace chars.
PARAMETERS:
strValue String to be trimmed.
RETURNS:
Source string with right whitespaces removed.
*************************************************/
var objRegExp = /^([\w\W]*)(\b\s*)$/;
if(objRegExp.test(strValue)) {
//remove trailing a whitespace characters
strValue = strValue.replace(objRegExp, '$1');
}
return strValue;
}
function leftTrim( strValue ) {
/************************************************
DESCRIPTION: Trims leading whitespace chars.
PARAMETERS:
strValue String to be trimmed
RETURNS:
Source string with left whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)(\b[\w\W]*)$/;
if(objRegExp.test(strValue)) {
//remove leading a whitespace characters
strValue = strValue.replace(objRegExp, '$2');
}
return strValue;
}
function trimAll( strValue ) {
/************************************************
DESCRIPTION: Removes leading and trailing spaces.
PARAMETERS: Source string from which spaces will

2.6 Replace a token by another in a string

be removed;
RETURNS: Source string with whitespaces removed.
*************************************************/
var objRegExp = /^(\s*)$/;
//check for all spaces
if(objRegExp.test(strValue)) {
strValue = strValue.replace(objRegExp, '');
if( strValue.length == 0)
return strValue;
}
//check for leading &trailing spaces
objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
if(objRegExp.test(strValue)) {
//remove leading and trailing whitespace characters
strValue = strValue.replace(objRegExp, '$2');
}
return strValue;
}
function removeCurrency( strValue ) {
/************************************************
DESCRIPTION: Removes currency formatting from
source string.
PARAMETERS:
strValue Source string from which currency formatting
will be removed;
RETURNS: Source string with commas removed.
*************************************************/
var objRegExp = /\(/;
var strMinus = '';
//check if negative
if(objRegExp.test(strValue)){
strMinus = '';
}
objRegExp = /\)|\(|[,]/g;
strValue = strValue.replace(objRegExp,'');
if(strValue.indexOf('$') >= 0){
strValue = strValue.substring(1, strValue.length);
}
return strMinus + strValue;
}
function addCurrency( strValue ) {
/************************************************
DESCRIPTION: Formats a number as currency.
PARAMETERS:
strValue Source string to be formatted
REMARKS: Assumes number passed is a valid
numeric value in the rounded to 2 decimal
places. If not, returns original value.
*************************************************/
var objRegExp = /?[09]+\.[09]{2}$/;
if( objRegExp.test(strValue)) {

2.6 Replace a token by another in a string

objRegExp.compile('^');
strValue = addCommas(strValue);
if (objRegExp.test(strValue)){
strValue = '(' + strValue.replace(objRegExp,'') + ')';
}
return '$' + strValue;
}
else
return strValue;
}
function removeCommas( strValue ) {
/************************************************
DESCRIPTION: Removes commas from source string.
PARAMETERS:
strValue Source string from which commas will
be removed;
RETURNS: Source string with commas removed.
*************************************************/
var objRegExp = /,/g; //search for commas globally
//replace all matches with empty strings
return strValue.replace(objRegExp,'');
}
function addCommas( strValue ) {
/************************************************
DESCRIPTION: Inserts commas into numeric string.
PARAMETERS:
strValue source string containing commas.
RETURNS: String modified with comma grouping if
source was all numeric, otherwise source is
returned.
REMARKS: Used with integers or numbers with
2 or less decimal places.
*************************************************/
var objRegExp = new RegExp('(?[09]+)([09]{3})');
//check for match to search criteria
while(objRegExp.test(strValue)) {
//replace original string with first group match,
//a comma, then second group match
strValue = strValue.replace(objRegExp, '$1,$2');
}
return strValue;
}
function removeCharacters( strValue, strMatchPattern ) {
/************************************************
DESCRIPTION: Removes characters from a source string
based upon matches of the supplied pattern.
PARAMETERS:
strValue source string containing number.
RETURNS: String modified with characters
matching search pattern removed

2.6 Replace a token by another in a string

USAGE:

strNoSpaces = removeCharacters( ' sfdf dfd',


'\s*')
*************************************************/
var objRegExp = new RegExp( strMatchPattern, 'gi' );
//replace passed pattern matches with blanks
return strValue.replace(objRegExp,'');
}
You can try it here.

If you want to know more about these MSDN pages :


RegExp Object
Regular Expression Syntax

2.6 Replace a token by another in a string

3 Common expressions
Date
/^\d{1,2}(\|\/|\.)\d{1,2}\1\d{4}$/

mm/dd/yyyy

US zip code
/(^\d{5}$)|(^\d{5}\d{4}$)/

99999 or 999999999

Canadian postal code


/^\D{1}\d{1}\D{1}\?\d{1}\D{1}\d{1}$/

Z5Z5Z5 orZ5Z5Z5

Time
/^([19]|1[02]):[05]\d(:[05]\d(\.\d{1,3})?)?$/

HH:MM or HH:MM:SS or HH:MM:SS.mmm

IP Address(no check for alid values (0255))


/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ 999.999.999.999
Dollar Amount
/^((\$\d*)|(\$\d*\.\d{2})|(\d*)|(\d*\.\d{2}))$/ 100, 100.00, $100 or $100.00
Social Security Number
/^\d{3}\?\d{2}\?\d{4}$/

999999999 or999999999

Canadian Social Insurance Number


/^\d{9}$/ 999999999
If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982005


[ home ]

3.1 Format a number as Money


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0076.html
function formatAsMoney(mnt) {
mnt = 0;
mnt = (Math.round(mnt*100))/100;
return (mnt == Math.floor(mnt)) ? mnt + '.00'
: ( (mnt*10 == Math.floor(mnt*10)) ?
mnt + '0' : mnt);
}

3.2 Have year on 4 digits from a Date object


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0044.html
function getYear(d) {
// Y2Kcompliant and compatible IE and NS
//
d a Date object
// returns a string
return (d=d.getYear())<1000 ? 1900+d : d

3 Common expressions

3.3 Validate a date


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0048.html
<HTML><HEAD>
<SCRIPT>
function getYear(d) {
return (d < 1000) ? d + 1900 : d;
}
function isDate (year, month, day) {
// month argument must be in the range 1 12
month = month 1; // javascript month range : 0 11
var tempDate = new Date(year,month,day);
if ( (getYear(tempDate.getYear()) == year) &
(month == tempDate.getMonth()) &
(day == tempDate.getDate()) )
return true;
else
return false
}
if (isDate(1997, 2, 28))
alert("19970231 is valid!");
else
alert("19970231 is invalid!");
</SCRIPT></HEAD><BODY>test date</BODY>
<HTML>

3.4 Useful Date functions


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0068.html
function getDaysInMonth(aDate){
// returns the last day of a given month
var m = new Number(aDate.getMonth());
var y = new Number(aDate.getYear());
var tmpDate = new Date(y, m, 28);
var checkMonth = tmpDate.getMonth();
var lastDay = 27;
while(lastDay <= 31){
temp = tmpDate.setDate(lastDay + 1);
if(checkMonth != tmpDate.getMonth())
break;
lastDay++
}
return lastDay;
}
function dateFormat(aDate, displayPat){
/********************************************************

3.3 Validate a date

*
Valid Masks:
*
!mmmm = Long month (eg. January)
*
!mmm = Short month (eg. Jan)
*
!mm = Numeric date (eg. 07)
*
!m = Numeric date (eg. 7)
*
!dddd = Long day (eg. Monday)
*
!ddd = Short day (eg. Mon)
*
!dd = Numeric day (eg. 07)
*
!d = Numeric day (eg. 7)
*
!yyyy = Year (eg. 1999)
*
!yy = Year (eg. 99)
********************************************************/
intMonth = aDate.getMonth();
intDate = aDate.getDate();
intDay = aDate.getDay();
intYear = aDate.getFullYear();
var months_long = new Array ('January','February','March','April',
'May','June','July','August','September','October','November',
'December')
var months_short = new Array('Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec')
var days_long = new Array('Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday')
var days_short = new Array('Sun','Mon','Tue','Wed','Thu','Fri',
'Sat')
var
var
var
var
var
var
var
var
var

mmmm = months_long[intMonth]
mmm = months_short[intMonth]
mm = intMonth < 9?'0'+ (1 + intMonth) + '':(1+intMonth)+'';
m = 1+intMonth+'';
dddd = days_long[intDay];
ddd = days_short[intDay];
dd = intDate<10?'0'+intDate+'':intDate+'';
d = intDate+'';
yyyy = intYear;

century = 0;
while((intYearcentury)>=100)
century = century + 100;
var yy = intYear century
if(yy<10)
yy = '0' + yy + '';
displayDate = new String(displayPat);
displayDate
displayDate
displayDate
displayDate
displayDate
displayDate
displayDate
displayDate
displayDate
displayDate

=
=
=
=
=
=
=
=
=
=

displayDate.replace(/!mmmm/i,mmmm);
displayDate.replace(/!mmm/i,mmm);
displayDate.replace(/!mm/i,mm);
displayDate.replace(/!m/i,m);
displayDate.replace(/!dddd/i,dddd);
displayDate.replace(/!ddd/i,ddd);
displayDate.replace(/!dd/i,dd);
displayDate.replace(/!d/i,d);
displayDate.replace(/!yyyy/i,yyyy);
displayDate.replace(/!yy/i,yy);

return displayDate;
}
// demo

3.3 Validate a date

alert(dateFormat(new Date() , "!yyyy !dd !mmm"))

Written and compiled Ral Gagnon 2007 real@rgagnon.com


http://www.rgagnon.com

3.3 Validate a date

4 Varia
4.1 jsvaria

4.2 Open a window with the right dimension for an image


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0094.html
<script language='javascript'>
function display(myimage) {
html = "<HTML><HEAD><TITLE>Photo</TITLE>" +
"</HEAD><BODY LEFTMARGIN=0 "
+ "MARGINWIDTH=0 TOPMARGIN=0 MARGINHEIGHT=0><CENTER>"
+ "<IMG SRC='" + myimage + "' BORDER=0 NAME=image "
+ "onload='window.resizeTo(document.image.width,document.image.height)'>"
+ "</CENTER>"
+ "</BODY></HTML>";
popup=
window.open
('','image',
'toolbar=0,location=0,directories=0,menuBar=0,scrollbars=0,resizable=1');
popup.document.open();
popup.document.write(html);
popup.document.focus();
popup.document.close()
};
/SCRIPT

Use it this way :


<a href="javascript:display('../images/jsht.gif')">Javascript HowTo 1</a>
<a href="javascript:display('../images/jsht2.gif')">Javascript HowTo 2</a>

Try it here : Javascript HowTo 1


Javascript HowTo 2

4.3 Detect if cookies are enabled


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0092.html
<SCRIPT LANGUAGE="JAVASCRIPT">
<!
var tmpcookie = new Date();
chkcookie = (tmpcookie.getTime() + '');
document.cookie = "chkcookie=" + chkcookie + "; path=/";
if (document.cookie.indexOf(chkcookie,0) < 0) {
window.location = 'nocookies.html';
}
else {
window.location = 'cookies.html';

4 Varia

}
//>
</SCRIPT>

4.4 Make a switch to another page after a delay


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0005.html
Actually there is no Javascript for this trick, only HTML!
<META HTTPEQUIV="refresh"
CONTENT="5;URL=http://www.somewhere.com/aPage.html">

"content" is the delay in seconds. Here we will wait 5 seconds before jumping to the specified URL.
To autorefresh (reload) a page after the delay, the HTML solution is still good. A JAVASCRIPT
alternative would be :
<SCRIPT>
function aReload() {
location.reload(true);
}
function startReload() {
setTimeout("aReload()", 5000);
}
</SCRIPT>
<BODY onLoad="startReload();">

4.5 Make sure that a page is displayed in a Frame


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0010.html
<html>
<head>
<SCRIPT LANGUAGE="JavaScript">
<!
if (parent.location.href == self.location.href)
window.location.href = 'index.html'; // contains the FRAMESET definitions
//>
</SCRIPT>
<BODY>
You can't see this without frames!
</BODY>
</HTML>
note : replace "index.html" by your "framehandler" page

4.4 Make a switch to another page after a delay

4.6 Make sure that a page is not displayed in a Frame


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0011.html
<SCRIPT>
function checkStatus() {
page = self.location.href;
if (page != top.location.href) {
top.location.href = page;
return true;
}
}
</SCRIPT>
<BODY onLoad="checkStatus()";>

4.7 Send email without CGI


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0012.html
Works with Netscape. The important thing is to NAME all the INPUT. The browser will prompt the
user that an email is about to be sent.
<FORM METHOD=POST
ACTION="mailto:someone@somewhere.com"
ENCTYPE="text/plain">
<INPUT TYPE="hidden" VALUE="1234" name="score">
<INPUT TYPE="hidden" VALUE="Mr. Smith" name="player">
<INPUT TYPE="submit" VALUE="Submit">
</FORM>

To set the subject :


ACTION="MAILTO:SOMEONE@SOMEWHERE.COM?SUBJECT=AUTOMATIC_EMAIL"

To send a Carbon Copy of the message to a second person, use the "cc" parameter :
<FORM METHOD=POST
ACTION="mailto:someone@somewhere.com?subject=importantomewhere.com"
ENCTYPE="text/plain">
<INPUT TYPE="submit" VALUE="Submit">
/FORM

While you can use a FORM to define the message body, it's also possible to define the body directly
in the mailto: URL :
mailto:someone@somewhere.com?body=HelloWorld

Thanks to Aneesha Bakharia for the following tip :


I've seen Javascript being used to neatly format form data so that it can be received in a readable
manner. This tip achieves a similar outcome but requires no Javascript at all. Simply add
ENCTYPE="text/plain" into the opening form tag. Remember to name all your form elements. Here
4.6 Make sure that a page is not displayed in a Frame

is the HTML for a sample form you could use to hire me as a web developer:
<form METHOD="POST" ENCTYPE="text/plain"
action="mailto:bakharia@squirrel.com.au">
<input type="hidden" name="Type of Form" value="Employment">
<table border="0" width="80%">
<tr>
<td width="197" valign="top">
<b>Enter Your Name:</b></td>
<td width="462">
<input type="text" name="Name" SIZE="50" MAXLENGTH="50">
</td>
</tr>
<tr>
<td width="197" valign="top">
<b>Enter your Email address:</b>
</td>
<td width="462">
<input type="text" name="Email" SIZE="50" MAXLENGTH="50">
</td>
</tr>
<tr>
<td width="197" valign="top">
<b>Your Request:</b>
</td>
<td width="462">
<textarea name="Comment" wrap="physical" rows="7" cols="48">
</textarea>
</td>
</tr>
<tr>
<td width="535" colspan="2">
<b><div align="center"><center><p></b>
<input type="submit" VALUE="Send Form">
<input type="reset" Value="Reset Form">
</td>
</tr>
</table>
</form>

Here is what your email will look like:


Type of Form=Employment
Name=Your Name goes here
Email=Your email address here too
Comment=Make a comment

4.8 Send email with attachment


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0013.html
Netscape only
<FORM ACTION="mailto:someone@somewhere.com?subject=REPORT"
METHOD="POST" ENCTYPE="multipart/formdata">
<INPUT TYPE="FILE" NAME="myReportFile" SIZE="70"><BR>
<INPUT TYPE="SUBMIT">
</FORM>

4.8 Send email with attachment

4.9 Instruct the browser to bypass the Cache


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0014.html
Put that in the HEAD section of the HTML page
<META HTTPEQUIV="Pragma" CONTENT="nocache">
<META HTTPEQUIV="Expires" CONTENT="1">

However, MS IE (almost all versions) do not process the instruction properly due to the cache
mechanism.
The workaround is to included a second <HEAD> section at the bottom of the page (no joke!).
<HTML><HEAD>
<META HTTPEQUIV="PRAGMA" CONTENT="NOCACHE">
<META HTTPEQUIV="Expires" CONTENT="1">
<META HTTPEQUIV="REFRESH" CONTENT="5">
<TITLE> Demonstration Pragma Nocache </TITLE>
</HEAD><BODY>
This page has 2 HEAD sections to properly bypass the cache in all browser.
</BODY>
<HEAD>
<META HTTPEQUIV="PRAGMA" CONTENT="NOCACHE">
<META HTTPEQUIV="Expires" CONTENT="1">
</HEAD>
</HTML>
NOTE: the above example uses META HTTPEQUIV="REFRESH" to make the browser reload the page automatically after 5 seconds, this is
for demonstration purpose only (to see that the cache is actually bypassed). This has nothing with the bypassing of the cache itself.

ref : http://support.microsoft.com/kb/q222064/
See also this HowTo.

4.10 Use a JAVASCRIPT username/password instead the


browser's one
Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0021.html
URL can be constructed with a special syntax to include an username and password. The format is
username:password@www.server.com. The URL is protected using the mechanism included with
the web server.
<HTML><HEAD>
<SCRIPT>
var targetUrl="www.server.com/protect/default.html";
function login() {
if (validLogin()) {
password = document.userInfos.username.value;

4.9 Instruct the browser to bypass the Cache

username = document.userInfos.password.value;
self.location.href=
"http://"+username+":"+password+"@"+targetUrl;
}
}
function validLogin() {
if (isBlank(document.userInfos.username.value)){
alert("Can't be blank");
document.userInfos.username.focus();
return false;
}
if (isBlank(document.userInfos.password.value)){
alert("Can't be blank");
document.userInfos.password.focus();
return false;
}
return true;
}
function isBlank(s) {
return (s == "");
}
</SCRIPT>
<BODY onLoad="document.userInfos.username.focus();">
<H1><CENTER>Identification </H1></CENTER>
<CENTER><TABLE BORDER=1>
<FORM NAME=userInfos>
<TR><TD>User: </TD><TD>
<INPUT TYPE="text" NAME=username LENGTH=20></TD></TR>
<TR><TD>Password: </TD><TD>
<INPUT TYPE="password" NAME=password LENGTH=20>
</TD></TR>
<TR ALIGN=center>
<TD></TD><TD>
<INPUT TYPE="button" VALUE="Ok" onClick="login()">
</TD></TR></TABLE></FORM></CENTER></BODY></HTML>

4.11 Force a reload


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0031.html
An easy way to force a reload (without using the browser cache) is to add a dummy parameter to
URL request.
dummyDate = new Date() ;
dummyParameter = "?" + dummyDate.getTime()
self.location.href = "myPage.html" + "?" + dummyParameter

The dummyParameter must be different for each request.


This tip is ok for static html or jsp/asp page.
See also this HowTo

4.11 Force a reload

4.12 Detect user resolution


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0040.html
function isLowRes() {
/*
** Check if the browser is running in a lowresolution environment
** try to use the screen object (in N4 or e4). If not available,
** try to use Java.If not available, assume lowres.
** returns true if in a lowresolution environment (width < 800 pixels)
*/
if (self.screen)
return (screen.width < 800);
else
if (navigator.javaEnabled &navigator.javaEnabled())
return
(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width <800);
else
return true;
}

4.13 Trigger a submit with Enter


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0046.html
The trick is to use 2 forms. The first one contains all the fields except the last one. The second form
contains the last field and in the submit function, we read the values from the first form and put them
in hidden fields defined in the second form. After validation, the submit function returns true or false
to submit or not.
<HTML><HEAD>
<SCRIPT LANGUAGE="JavaScript">
function submit1() {
document.PwdForm.pwd.focus();
/* don't submit yet */
return false;
}
function submit2() {
document.PwdForm.username.value =
document.LoginForm.username.value;
/* perform any validation here */
/* and submit */
return true;
}
</SCRIPT>
</HEAD><BODY>
<FORM NAME="LoginForm" onSubmit="return submit1()">
<P>User Name: <INPUT NAME="username" TYPE="TEXT">
</FORM>
<FORM NAME="PwdForm" onSubmit="return submit2()">
<INPUT NAME="username" TYPE="HIDDEN">
<P>Password: <INPUT NAME="pwd" TYPE="PASSWORD">
</FORM>

4.12 Detect user resolution

</BODY></HTML>

4.14 Print the current page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0052.html
[Netscape 4 and IE4/5]
<SCRIPT>
function displayPrintButton() {
if ((navigator.appName.indexOf("Netscape") > 1 &
parseInt(navigator.appVersion) >= 4) ||
(navigator.appName.indexOf("Microsoft") > 1 &
parseInt(navigator.appVersion) >= 4) ) {
document.write
("<FORM><INPUT TYPE=button VALUE='Print' " +
"onClick='printCurrentPage();'></FORM>");
}
}
function printCurrentPage() {
if (navigator.appName.indexOf("Microsoft") > 1 &
navigator.appVersion.indexOf("5.") == 1) {
// IE4
OLECMDID_PRINT = 6;
OLECMDEXECOPT_DONTPROMPTUSER = 2;
OLECMDEXECOPT_PROMPTUSER = 1;
WebBrowser =
'<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="' +
'CLSID:8856F961340A11D0A96B00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID_PRINT,
OLECMDEXECOPT_PROMPTUSER);
WebBrowser1.outerHTML = "";
}
else {
// N4 IE5
window.print();
}
}
displayPrintButton();
</SCRIPT>

4.15 Add a bookmark


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0053.html
For IE4 or better only.
<script language="JavaScript">
<!
var bookmarkurl="http://www.rgagnon.com/howto.html"
var bookmarktitle="Real's HowTo"
function addbookmark(){

4.14 Print the current page

if (document.all)
window.external.AddFavorite(bookmarkurl,bookmarktitle)
}
>
</script>
<a href="javascript:addbookmark()">Add Real's HowTo to your Bookmarks</a>

Try it Add Real's HowTo to your Bookmarks


Alternate script :
<SCRIPT LANGUAGE = "JavaScript1.2">
if ((navigator.platform!="MacPPC") &(navigator.appName=="Microsoft
Internet Explorer") &(navigator.appVersion>="4")) {
document.write
("<A HREF='Javascript:window.external.AddFavorite(location.href,
document.title)'>Add my site to your Favorites</A>")}
</SCRIPT>

4.16 Detect plugins presence


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0056.html
There is no portable way to do it on all browsers. On Netscape, it's very straightforward. All we need
is to check plugins property.
For example, to detect if the RealPlayer is installed :
<SCRIPT>
numPlugins = navigator.plugins.length;
for (i = 0; i < numPlugins; i++)
{
plugin = navigator.plugins[i];
if (plugin.name.substring(0,10)=="RealPlayer")
{
alert("You have the RealPlayer Plugin installed!")
}
}
</SCRIPT>

With IE, we try to instanciate to corresponding COM object. If the object is null then we assume that
the plugin is missing. Again for the RealPlayer :
<SCRIPT LANGUAGE="VBScript">
on error resume next
RealPlayerG2 =
not IsNull(CreateObject("rmocx.RealPlayer G2 Control"))
RealPlayer5 =
not IsNull(CreateObject
("RealPlayer.RealPlayer(tm) ActiveX Control (32bit)"))
RealPlayer4 =
not IsNull(CreateObject
("RealVideo.RealVideo(tm) ActiveX Control (32bit)"))
if (RealPlayerG2 or RealPlayer5 or RealPlayer4) then
document.write "RealPlayer Ok"
else

4.16 Detect plugins presence

document.write "RealPlayer not found"


end if
</SCRIPT>

For Shockwave, detection will be like :


<SCRIPT LANGUAGE="Javascript">
<!
// detection for Netscape
var useFlash = navigator.mimeTypes &
navigator.mimeTypes["application/xshockwaveflash"] &
navigator.mimeTypes["application/xshockwaveflash"].enabledPlugin;
//>
</SCRIPT>
<SCRIPT LANGUAGE="VBScript">
<!
' detection for IE
On error resume next
useFlash = NOT IsNull(CreateObject("ShockwaveFlash.ShockwaveFlash"))
//>
</SCRIPT>
...
<SCRIPT LANGUAGE="Javascript">
<!
if ( useFlash ) {
document.write('<CENTER><embed SRC="mything.swf"
WIDTH="530" HEIGHT="523" align="center" LOOP="true"
QUALITY="high"></center>');
}
else {
document.write('NonShockwave');
}
//>
</SCRIPT>

Here a method to determine which ActiveX name to use.


Let's say we want to detect if the ActiveX object for Acrobat Reader is installed from IE. Start
RegEdit, go to HKEY_LOCAL_MACHINE\Software\CLASSES\ and locate the entries for the file
extension (pdf) used by Acrobat. The first key value gives the ActiveX object to use with IE,
AcroExch.Document, and the second the MIME type to be used with Netscape.
<SCRIPT LANGUAGE="Javascript">
<!
// detection for Netscape
var useAcrobat = navigator.mimeTypes &
navigator.mimeTypes["application/pdf"]
//>
</SCRIPT>
...
<SCRIPT LANGUAGE="VBScript">
<!
on error resume next
useAcrobat = not IsNull(CreateObject("AcroExch.Document"))
'
can be CreateObject("PDF.PdfCtrl.1") too!
//>
</SCRIPT>
<SCRIPT>
<!

4.16 Detect plugins presence

if (useAcrobat)
document.write("Acrobat reader ok");
else
document.write("Acrobat reader not found");
//>
</SCRIPT>

4.17 Detect missing image


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0083.html
From HTML tag :
<img src="picture1.gif" onerror="this.onerror=null;this.src='missing.gif';">

From script :
var imgsrc = 'picture1.gif';
var img = new Image();
img.onerror = function (evt) {
alert(this.src + " can't be loaded.");
}
img.onload = function (evt) {
alert(this.src + " is loaded.");
}
img.src = imgsrc;
If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982005


[ home ]

4.18 Pure javascript image


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0087.html
javascript:
'#define%20logo_width%2024\n#define%20logo_height%203\nstatic%20char%20logo_bits[]=
{\n0xFF,0xFF,0xFF,0xFF,0x00,0xFF,0xFF,0xFF,0xFF}'

try it here
Want to know what is going on ?
See these XBM related sites : Site 1 and Site 2

4.17 Detect missing image

4.19 Detect if the connection is possible via a secure channel


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0088.html
To see what JavaScript can tell you about Navigator, use this statement:
for (i in navigator) alert(i + " = " + navigator[i])

If the appVersion (or the userAgent) property end with ;U which designates USA/Canada, the
browser has the 128bit strong encryption.
If the property ends with ";I" which designates International, then the browser _probably_ does not.
var encryption =
navigator.appName != 'Netscape' ? 'unknown' :
navigator.userAgent.indexOf(' U') != 1 ? 'strong' : 'weak';
Note: for a java solution see this HowTo

4.20 Search a dropdown list


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0089.html
<HTML><HEAD><SCRIPT type="text/javascript">
function searchSel() {
var input=document.getElementById('realtxt').value.toLowerCase();
var output=document.getElementById('realitems').options;
for(var i=0;i<output.length;i++) {
if(output[i].value.indexOf(input)==0){
output[i].selected=true;
}
if(document.forms[0].realtxt.value==''){
output[0].selected=true;
}
}
}
</SCRIPT></HEAD><BODY>
<FORM>
Search <input type="text" id="realtxt" onkeyup="searchSel()">
<SELECT id="realitems">
<OPTION value="">Select...
<OPTION value="afghanistan">Afghanistan
<OPTION value="albania">Albania
<OPTION value="algeria">Algeria
<OPTION value="andorra">Andorra
<OPTION value="angola">Angola
</SELECT>
</FORM></BODY></HTML>

Search

4.19 Detect if the connection is possible via a secure channel

4.21 Carriage return in ALT tag


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0095.html
Works IE (not FF).
<img src="'../images/jsht.gif'"
alt="Javascript&#013;HowTo" title="Real's Javascript&#013;HowTo">

Here how it looks :

If you want sophisticated tooltip then take a look at the overLib javascript library at
http://www.bosrup.com/web/overlib/.

4.22 Encrypt data


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0097.html
http://www.shopable.co.uk/des.html
http://pajhome.org.uk/crypt/md5/

4.23 Erase a page without loading another page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0105.html
<HTML><HEAD><TITLE></TITLE></HEAD>
<BODY>
Yo!
<button onclick="document.location.href='about:blank'" >
erase me
</button>
<button onclick="location.replace('about:blank')" >
erase me (plus no history)
</button>
</BODY></HTML>

Try it : erase me erase me (plus no history)

4.24 Hilite a word in a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0109.html
4.21 Carriage return in ALT tag

<span id="hilitezone">
<table border="1">
<tr>
<td>Subscription to the mailing list is free of course.<br>
The main purpose of this mailing list is to keep you<br>
inform about updates to the Real's Howto site.<br>
<p>As a subscriber, you have access to a special<br>
download section where you can download PDF files<br>
containing the "Real's Howto" site for offline viewing.
</td></tr>
</table>
</span>
<form name="hiliteaword">
<input type="button" value="Hilite Howto" onClick="hilite()"></input>
<input type="button" value="no hilite" onClick="nohilite()"></input>
</form>
<script>
var originalzone=document.getElementById("hilitezone").innerHTML;
function hilite(){
if(document.getElementById &
document.getElementById("hilitezone") &
document.getElementById("hilitezone").innerHTML){
var newzone=originalzone.replace(/Howto/g,
'<span style="color:red;fontweight:bold">Howto</span>');
document.getElementById("hilitezone").innerHTML=newzone;
}
}
function nohilite(){
if(document.getElementById &
document.getElementById("hilitezone") &
document.getElementById("hilitezone").innerHTML){
document.getElementById("hilitezone").innerHTML=originalzone;
}
}
</script>

Try it !
Subscription to the mailing list is free of course.
The main purpose of this mailing list is to keep you
inform about updates to the Real's Howto site.
As a subscriber, you have access to a special
download section where you can download PDF files
containing the "Real's Howto" site for offline viewing.

4.25 Start an executable


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0111.html
IE only
<script>

4.25 Start an executable

function go() {
w = new ActiveXObject("WScript.Shell");
w.run('notepad.exe');
return true;
}
</script>
<form>
Run Notepad (Window with explorer only)
<input type="button" value="Go"
onClick="return go()">
/FORM

try it :
Run Notepad (Window with explorer only) NOTE: Works in a trusted environment like an intranet
(and certainly not from the internet!).
Here an interesting trick, this link will attempt to launch a notepad (if you are using Windows) and
load the win.ini in your C:\WINDOWS directory.

4.26 Pass data from a resultset to Javascript Array


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0117.html
On the serverside, the ASP code executes a query, the result is written in FORM hidden field
(each value is separated by a ","). Then from Javascript (on the clientside), each hidden field
value is extracted to an array,
Of course, JSP code can be used instead of ASP!
<%
'
'ASP (serverside)
'
Set Connection = Server.CreateObject("ADODB.Connection")
Connection.Open strConn
Set rs = Connection.Execute("SELECT field1, field2 from mytable")
Do While NOT rs.EOF
field1 = field1 &rs("field1") &","
field2 = field2 &rs("field2") &","
rs.MoveNext
loop
field1 = Left(field1,len(field1)1)
field2 = Left(field2,len(field2)1)
%>
<!HTML (clientside)>
<form name="dataholder" action="#">
<input type="hidden" name="field1" value="<%=field1%>">
<input type="hidden" name="field2" value="<%=field2%>">
</form>
<script language="JavaScript">

4.26 Pass data from a resultset to Javascript Array

var something = "";


//Fetch the data from the serverside
var field1 = document.dataholder.field1.value;
//returns an array
var arrField1 = field1.split(",");
var field2 = document.dataholder.field2.value;
var arrField2 = strField2.split(",");
for(var i=0; i < field1.length;i++) {
something += arrField1[i];
something += arrField2[i];
}
</script>

4.27 Disable Browser Context Menu


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0119.html
<SCRIPT type="text/javascript">
function disableContextMenu(element) {
element.oncontextmenu = function() {
return false;
}
}
function onLoad() {
disableContextMenu(document.getElementById("myimage"));
}
</SCRIPT>
...
<BODY onload="onLoad()">

On this image, you have context menu (rightclick)

On this image you have no context menu (rightclick)

NOTE: Works on IE but... on Firefox a setting can disable the ability for a script to block the
context menu

4.28 Disable text selection in a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0120.html
This javascript disables the ability to select text with mouse. You can try it on this page (works on
4.27 Disable Browser Context Menu

IE and FF).
<SCRIPT type="text/javascript">
if (typeof document.onselectstart!="undefined") {
document.onselectstart=new Function ("return false");
}
else{
document.onmousedown=new Function ("return false");
document.onmouseup=new Function ("return true");
}
</SCRIPT>

However, it's not a good "protection" because you can return to the normal behaviour with a
simple javascript url :
IE here to put back the mouse selection
FF here to put back the mouse selection

4.29 Use Excel


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0122.html
These scripts are for IE only
Launch Excel externally
<input type="button" value="excel (IE only)" onclick="startExcel();">
<script language="javascript">
function startExcel() {
var xls = new ActiveXObject ( "Excel.Application" );
xls.visible = true;
var newBook = xls.Workbooks.Add;
newBook.Worksheets.Add;
newBook.Worksheets(1).Activate;
newBook.Worksheets(1).Cells(1,1).value="First Column, First Cell";
newBook.Worksheets(1).Cells(2,1).value="First Column, Second Cell";
newBook.Worksheets(1).Cells(1,2).value="Second Column, First Cell";
newBook.Worksheets(1).Cells(2,2).value="Second Column, Second Cell";
newBook.Worksheets(1).Name="WorkSheet from Javascript";
// newBook.Worksheets(1).SaveAs("C:\\temp\\TEST2.XLS");
}
</script>

Try it here :
Excel embedded into the browser
You need a recent Office version with the OWC control installed. OWC means Office Web
Components.
In the registry (HKEY_CLASSES_ROOT\CLSID), you locate the CLSID (or CLASSID) key for
"Microsoft Office Spreadsheet 10.0" (if you have Office 10).
Typically
4.29 Use Excel

HKEY_CLASSES_ROOT\CLSID\{0002E54100000000C000000000000046}
"Microsoft Office Spreadsheet 10.0"

The CLSID is the weird looking number at the end of the key.
Then
<object
width = 900
height = 500
id = 'excel'
classid = 'CLSID:0002E54100000000C000000000000046' VIEWASTEXT>
<param name=DisplayTitleBar value=true >
<param name="DataType" value="CSVURL">
<param name="AutoFit" value="0">
<param name="DisplayColHeaders" value="1">
<param name="DisplayGridlines" value="1">
<param name="DisplayHorizontalScrollBar" value="1">
<param name="DisplayRowHeaders" value="1">
<param name="DisplayTitleBar" value="1">
<param name="DisplayToolbar" value="1">
<param name="DisplayVerticalScrollBar" value="1">
<param name="EnableAutoCalculate" value="0">
<param name="EnableEvents" value="0">
<param name="MoveAfterReturn" value="1">
<param name="MoveAfterReturnDirection" value="0">
<param name="RightToLeft" value="0">
<param name="XMLURL" value="http://www.rgagnon.com/examples/xls/hello.xml">
</object>
<xparam name="HTMLURL" value="http://www.rgagnon.com/examples/xls/t1.html">
<xparam name="csvURL" value="http://www.rgagnon.com/examples/xls/t2.csv">
<script>
excel.range('a14').value
excel.range('b14').value
excel.range('c14').value
excel.range('d14').value
excel.range('e14').value
</script>

=
=
=
=
=

'435';
'0';
'yop!';
'yip!';
'';

<script>
function boldexcel(){
excel.ActiveCell.EntireRow.Font.Bold = true;
}
function excelalert(){
alert(excel.ActiveCell.Value);
}
function excelview(){
excel.ViewableRange="$A$1:$C$4";
}
</script>
<p>
<button onclick="boldexcel()">bold</button>
<button onclick="excelalert()">alert</button>
<button onclick="excelview()">view</button>

Try it here (for IE only and Office 10).


Note :

OWC can not open XLS, only XML or HTML format.


OWC9 Spreadsheet control supports only a single sheet
4.29 Use Excel

OWC10 Spreadsheet control supports multiple worksheets.

4.30 Generate a bar chart


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0135.html
Vertical bar
' + data[i][1] + '
' + data[i][0] +'
');
<html>
<head></head>
<body>
<script>
var data = [
['jan', 10], ['feb', 50], ['mar', 30] ,
['apr', 100], ['may', 50], ['jun', 110] ,
['jul', 40], ['aug', 50], ['sep', 70] ,
['oct', 80], ['nov', 20], ['dec', 80]
];
document.write('<table border="0"><tr>');
for (var i=0; i < data.length; ++i)
document.write(
'<td align="center" valign="bottom">'
+ data[i][1]
+ '<div style="background:red;width:20px;height:'
+ data[i][1] + 'px"> </div>'
+ data[i][0] +'</td>');
document.write('</tr></table>');
</script>
</body>
</html>

Horizontal bar
' + data[i][0] +' ' + data[i][1]); document.write('
');
<html>
<head></head>
<body>
<script>
var data = [
['jan', 10], ['feb', 50], ['mar', 30] ,
['apr', 100], ['may', 50], ['jun', 110] ,
['jul', 40], ['aug', 50], ['sep', 70] ,
['oct', 80], ['nov', 20], ['dec', 80]
];

4.30 Generate a bar chart

document.write('<table border="0">');
for (var i=0; i < data.length; ++i)
document.write(
'<tr><td>' + data[i][0]
+'<td><hr id="red" style="height: .8em; '
+ 'backgroundcolor: red; color: red; '
+ 'marginleft: 0; textalign: left; '
+ 'width: ' + data[i][1] + 'px"/><td>' + data[i][1]);
document.write('</tr></table>');
</script>
</body>
</html>

See this HowTo to generate a bar chart using Google Chart API.

4.31 Generate a bar chart (with Google Chart)


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0136.html
Vertical bar
It's easy to use the Google Chart API to generate a graph.
The code is located on the Google server and you build a URL with all the parameters. Once the
URL is received by Google, an image is returned.
Be prepared, "trial and error" is the way to get the thing done!
var data = [
['jan', 10], ['feb', 50], ['mar', 30] ,
['apr', 100], ['may', 50], ['jun', 100] ,
['jul', 40], ['aug', 50], ['sep', 70] ,
['oct', 80], ['nov', 20], ['dec', 80]
];
document.write('<img src="http://chart.apis.google.com/chart?'
+ 'chs=400x200' // graphic size
+ '&amp;cht=bvs' // bar vertical chart
+ '&amp;chco=ff0000'
// color
+ '&amp;chd=t:');
// data
for (var i=0; i < data.length; ++i) {
document.write(data[i][1]);
if (i < data.length1) document.write(",");
}
document.write('&amp;chxt=x,y');
// axis : x bottom y left
document.write('&amp;chxl=0:|');
for (var i=0; i < data.length; ++i) { // the labels
document.write(data[i][0]);
if (i < data.length1) document.write("|");
}
document.write('&amp;chxr=1,0,100');
document.write('">');

4.31 Generate a bar chart (with Google Chart)

The result :
Horizontal bar
var data = [
['jan', 10], ['feb', 50], ['mar', 30] ,
['apr', 100], ['may', 50], ['jun', 100] ,
['jul', 40], ['aug', 50], ['sep', 70] ,
['oct', 80], ['nov', 20], ['dec', 80]
];
document.write('<img src="http://chart.apis.google.com/chart?'
+ 'chs=200x300'
+ '&amp;cht=bhs'
+ '&amp;chco=ff0000'
+ '&amp;chd=t:');
for (var i=0; i < data.length; ++i) {
document.write(data[i][1]);
if (i < data.length1) document.write(",");
}
document.write('&amp;chxt=y,x'); // left , bottom
document.write('&amp;chxl=0:|');
for (var i=data.length1; i >= 0 ; i) {
document.write(data[i][0]);
if (i > 0) document.write("|");
}
document.write('&amp;chxr=1,0,100');
document.write('">');

The result :
Important : When you embed a URL in an HTML <img> tag, take care to use the character entity
reference &amp; in place of an ampersand (&).
See this HowTo to generate a bar chart using plain Javascript.

4.32 Load an HTML page depending on the browser type


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0003.html
<SCRIPT>
if (navigator.appName == "Microsoft Internet Explorer")
document.write('<META HTTPEQUIV="REFRESH" CONTENT="1;URL=msie.html">');
else
document.write('<META HTTPEQUIV="REFRESH" CONTENT="1;URL=netscape.html">');
</SCRIPT>

The browser version can be obtain with


browserversion = parseint(navigator.appversion);

4.32 Load an HTML page depending on the browser type

4.33 Detect browser type


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0039.html

4.33.1 Detecting if a feature is present or not


We test for a known feature to decide the browser type.
ns = (document.layers) ? true : false;
ie = (document.all) ? true : false;
ff = document.getElementById? true : false;
if (ie) document.write("Internet Explorer");
else if (ff) document.write("Firefox");
else if (ns) document.write("Netscape");
else document.write("Unknown browser !!!");

With this browser, this code gives :

4.33.2 Use a conditionnal comment


See this HowTo

4.33.3 Use the browser name


This technique is not very good because a browser can alter its name to allow a better
compatibility.
<HTML>
<HEAD>
<SCRIPT LANGUAGE= "JavaScript">
function isNetscape(v) {
/*
** Check if the browser is Netscape compatible
**
v version number
** returns true if Netscape and version equals or greater
*/
return isBrowser("Netscape", v);
}
function isMicrosoft(v) {
/*
** Check if the browser is Microsoft Internet Explorer compatible
**
v version number
** returns true if MSIE and version equals or greater
*/
return isBrowser("Microsoft", v);
}
function isBrowser(b,v) {
/*
** Check if the current browser is compatible
** b browser name
** v version number (if 0 don't check version)
** returns true if browser equals and version equals or greater
*/
browserOk = false;
versionOk = false;

4.33 Detect browser type


browserOk = (navigator.appName.indexOf(b) != 1);
if (v == 0) versionOk = true;
else versionOk = (v <= parseInt(navigator.appVersion));
return browserOk &versionOk;
}
</SCRIPT></HEAD><BODY><FORM>
<INPUT TYPE="button"
VALUE="Test for Netscape 4"
onClick="alert(isBrowser('Netscape', 4));">
<INPUT TYPE="button"
VALUE="Test for IE3"
onClick="alert(isBrowser('Explorer', 0));">
</FORM></BODY></HTML>
For more complete script to detect browser version, check the Netscape site

4.34 Allow IE to execute javascript from a local file


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0123.html
By default, IE6 blocks javascript execution from a local HTML file and asks whether to allow
'blocked content'.
To allow local execution :
Tools > Internet Options > Advanced Tab > Allow Active Content

There are two boxes there to be checked :


one is for the PC
one is for the CD Drive.

4.35 Make IE8 behave like IE7


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0138.html
By default, IE8 is more standard compliant than IE7. This fact can make some pages to not
render correctly if they are designed with IE7 specific behavior.
You can tell to IE8 to render a page like IE7 by adding a special META tag in the HEAD section.
<html>
<head>
<meta httpequiv="XUACompatible" content="IE=EmulateIE7"/>
</head>
<body>Renders the same in IE8 as it did in IE7</body>
</html>

ref : http://msdn.microsoft.com/enus/library/cc817570.aspx

4.34 Allow IE to execute javascript from a local file

4.36 Detect Internet Explorer


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0137.html
<html>
<body>
<![if IE]>
<h1> Internet Explorer</h1>
<![endif]>

<![if !IE]> <>


<h1>NOT Internet Explorer</h1>
<!> <![endif]>
</body>
</html>

With the browser used to view this page, the result is :

4.36 Detect Internet Explorer

5 NOT Internet Explorer


This technique is using conditional comments, They only work in Internet Explorer on Windows,
and are thus excellently suited to give special instructions meant only for Internet Explorer on
Windows. All other browsers will see them as normal comments and will ignore them entirely.
It's possible to detect the IE version too.
<script>
var isIE = false;
var version = 1;
</script>
<![if IE 6]>
<script>
isIE = true;
version = 6
</script>
<![endif]>
<![if IE 7]>
<script>
isIE = true;
version = 7
</script>
<![endif]>
With the browser used to view this page, the result is :<br>
<script>
document.write("IE : " + isIE + "<br>");
document.write("version : " + version + "<br>");
</script>

With the browser used to view this page, the result is :


See also this HowTo.

5.1 Protect a page access with JAVASCRIPT only


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0022.html
If the password protection mechanism provided by the Web server is not available, a simple way
to protect a page with JAVASCRIPT is to match the user password with the filename to be
loaded.
<HTML><HEAD>
<SCRIPT>
function login() {
if (validLogin()) {
password = document.userInfos.password.value;
self.location.href=
"http://www.server.com/login/"+password+".html";
}
}
function validLogin() {
if (isBlank(document.userInfos.password.value)){

5 NOT Internet Explorer

alert("Can't be blank");
document.userInfos.password.focus();
return false;
}
return true;
}
function isBlank(s) {
return (s == "");
}
</SCRIPT>
<BODY onLoad="document.userInfos.password.focus();">
<H1><CENTER>Identification </H1></CENTER>
<CENTER><TABLE BORDER=1>
<FORM NAME=userInfos>
<TR><TD>Password: </TD><TD>
<INPUT TYPE="password" NAME=password LENGTH=20>
</TD></TR>
<TR ALIGN=center>
<TD></TD><TD>
<INPUT TYPE="button" VALUE="Ok" onClick="login()">
</TD></TR></TABLE></FORM></CENTER></BODY></HTML>

5.2 Associate an Icon to Favorites (IE5)


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0058.html
There is no javascript for this. Upload your ICO file to be associated to your site. Then the
following line in the first page to be loaded :
<LINK REL="SHORTCUT ICON"
HREF="http://www.myserver.com/mysite/favicon.ico">

When a user will bookmark your site, the favorite icon will be associated. Right now only IE5
supports this feature. The ICO must be 16x16 in 16 colors.

5.3 Execute a javascript function by clicking on text


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0069.html
<script>
function a() {
alert("Hello")
}
</script>
<a onClick="a();" style="cursor: pointer; cursor: hand;">*click here*</a>

Try it here : *click here*


NOTE : The style "cursor: pointer" works in Mozilla and Netscape 6+, IE6/Win, and IE5.x/Mac, but
not IE5.x/Win where the "cursor: pointer" must be used. IE6/Win and IE5.x/Mac accept both the
"pointer" and "hand"! That's why we are using "cursor: pointer; cursor: hand;". Do not reverse
5.2 Associate an Icon to Favorites (IE5)

those two values! Written this way, NS6+ will see the first value and ignore the second, so you get
pointer. In IE5.x/Win, it sees both and uses the second, so you get hand. If you reverse the
values, then Netscape 6+ will be okay, but IE5.x/Win will see both and try to use the second. That
won't get you the little handpointer icon in IE5.x/Win.
using SPAN
<span id="SpecialSpan"
onmouseover="this.style.cursor='pointer'"
onmouseout="this.style.cursor='default'"
onclick="a()";>
*click here*
</span>

Try it here : *click here*


The possible values for the cursor are
hand (IE)
pointer (N)
auto (N6)
crosshair
default (arrow)
move
n|ne|e|se|s|sw|w|nwresize
text (Ibar)(N6)
wait (hour glass)(N6)
help (arrow with"?")

5.4 Use the new <BUTTON> tag


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0077.html
The new BUTTON tag makes it easy to create button.
With color and formatting
Howto

Real's

<BUTTON><FONT COLOR="#ff0000"><B>Real's<BR>Howto</B></FONT></BUTTON>

Or with an image

<BUTTON onClick="alert('www.rgagnon.com')"><IMG SRC="../images/realhowtoleft.jpg"></BUTTON>

5.5 Protect an image


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0090.html
You can make it a little bit harder by placing over an image (to be protected) a transparent GIF.
5.4 Use the new <BUTTON> tag

<span style=
"backgroundimage:
url('images/realhowto.gif'); backgroundrepeat: norepeat;">
<img src="images/transparent.gif" width="16" height=16"
border="0" alt="RealHowTo">
</span>

Try to save this image with a rightclick :

5.6 Have fixed visible URL


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0099.html
Use FRAMESET with only one defined FRAME, the visible URL will always be the FRAMESET
page.
<HTML>
<HEAD>
<TITLE>Visible URL is always the same</TITLE>
<FRAMESET rows="100%,*">
<FRAME src="pagea.html">
</FRAMESET>
</HEAD>
/HTML
<HTML>
<HEAD>
<TITLE>PAGE A</TITLE>
</HEAD>
<BODY>
pagea
<p><a href="pageb.html">pageb</a>
</BODY>
/HTML
<HTML>
<HEAD>
<TITLE>PAGE B</TITLE>
</HEAD>
<BODY>
pageb
<p><a href="pagea.html">pagea</a>
</BODY>
/HTML

Try it here

5.6 Have fixed visible URL

5.7 Disable IE6 image toolbar


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0100.html
For the complete page
<META httpequiv="imagetoolbar" content="no" />

For only one element


<IMG src="realhowto.gif" galleryimg="no" />

5.8 Make a link to see the source of a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0106.html
See this
<html>
<head>
<title>viewsource demo</title>
</head>
<body>
<a href="viewsource:http://www.rgagnon.com/examples/viewsource.htm">
view my source</a>
</body>
</html>

You have to specify the full "path", relative url won't work with the viewsource protocol.
With some Javascript, you can bypass this limitation if the "full" path is not known.
<a href="example1.htm" onclick="location.href = 'viewsource:'
+ this.href; return false">example1.htm</a>

Try it here
Thanks to John TaylorJohnston for this tip.

5.9 Cool page transition


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0073.html
These special effects are available only with IE4 or better.
Using special META tags in the HEAD portion of your page, very special effect can be achieved.

5.7 Disable IE6 image toolbar

<META HTTPEQUIV="PageEnter" CONTENT="RevealTrans (Duration=1, Transition=23)">

Try this example here


You can use these transitions to create effects on either page entry or exit as specified in the
META.
The transitions available are :
Box in
0
Box out
1
Circle in
2
Circle out 3
Wipe up
4
Wipe down
5
Wipe right 6
Wipe left
7
Vertical blinds
8
Horizontal blinds
9
Checkerboard across 10
Checkerboard down
11
Random dissolve
12
Split vertical in
13
Split vertical out
14
Split horizontal in 15
Split horizontal out 16
Strips left down
17
Strips left up
18
Strips right down
19
Strips right up
20
Random bars horizontal 21
Random bars vertical
22
Random 23

Another cool effect (as seen on this page!) is


<META HTTPEQUIV="PageEnter" CONTENT="blendTrans(Duration=0.4)">
<META HTTPEQUIV="PageExit" CONTENT="blendTrans(Duration=0.4)">
But remember these effects work only with IE.

5.10 Cool FORM tips


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0114.html
Here some little known HTML tags to enhance the look and feel of HTML FORM.
The first one is the tag LABEL. This tag is used to attach a label to a component.
If you use something like this :
<FORM>
Name <INPUT TYPE="text" ID="fname" VALUE="">
</FORM>

5.10 Cool FORM tips

The result is
Name You need to click in the field to give focus and be able to type something.
If you attach a LABEL to a field then you can click the label (or the field) and then the attached
component will gain the focus.
<FORM>
<LABEL
<INPUT
<BR>
<LABEL
<INPUT
Choose
<INPUT
<LABEL
<INPUT
<LABEL
</FORM>

FOR="tf1">Name </LABEL>
TYPE="text" ID="tf1" VALUE="">
FOR="tf2">Email</LABEL>
TYPE="text" ID="tf2" VALUE=""><br><BR>
<LABEL FOR="rb1">Yes</LABEL> or <LABEL FOR="rb2">No</LABEL>
ID="rb1" NAME="nlrb" TYPE="radio" VALUE="yes">
FOR="rb1"> Yes</LABEL>
ID="rb2" NAME="nlrb" TYPE="radio" VALUE="no">
FOR="rb2">No</LABEL>

You can try it here :


Name (click here)
Email (or here)
Choose Yes or No Yes (click here) No (or here too)
The FIELDSET defines a group of form elements as being logically related. The browser draws a
box around the set of fields to indicate that they are related.
<FORM>
<FIELDSET>
Name <INPUT TYPE="text" ID="name" VALUE="">
Email<INPUT TYPE="text" ID="email" VALUE="">
</FIELDSET>
</FORM>

Here how it looks :


Name Email
It is possible to put a title with the tag LEGEND.
<FORM>
<FIELDSET STYLE="width : 45%; ">
<LEGEND>Contact us</LEGEND>
<label for="name2">Name </label>Name <INPUT TYPE="text" ID="name2" VALUE=""> <br>
<label for="email2">Email</label>Email<INPUT TYPE="text" ID="email2" VALUE="">
</FIELDSET>
</FORM>

Here how it looks (with STYLE to limit the width):


Contact us Name
Email

5.10 Cool FORM tips

And finally, you can make the SUBMIT button a little less boring...
<STYLE TYPE="text/css">
input.howto {
backgroundcolor: #FFFFCC;
fontweight: bold;
fontsize: 12px;
color: black;}
</STYLE>
<FORM>
<FIELDSET STYLE="width : 45%; ">
<LEGEND><B>Type your query</B></LEGEND>
<LABEL FOR="query">Name </LABEL> <INPUT TYPE="text" ID="query" VALUE="">
<INPUT CLASS="howto" TYPE="submit" VALUE="Submit">
</FIELDSET>
</FORM>

input.howto { backgroundcolor: #FFFFCC; fontweight: bold; fontsize: 12px; color: black;}


Here how it looks :
Type your query Name

5.11 Display tooltip in HTML


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0121.html
The TITLE attribute in almost every HTML tag is used to display a tooltip.
<html><body>
<img src="../images/gumby.gif" title="My name is Gumby">
<p>
<a href="http://www.google.com"
title="The Google Search Engine">Google</a>
<p>
<table title="Sales Figures">
<caption>Jan 2007</caption>
<tr title="row 1"><td>111111<td>222222
<tr><td>333333<td title="col 4">444444
</table>
</body></table>
<form>
<input type="text" size=25 title="Enter your email address here">
<input type="button" value="Submit" title="Click to submit!">
</form>
<div title="End of this HowTo">End.</div>

It looks like

Google
Jan 2007
5.11 Display tooltip in HTML

111111 222222
333333 444444
End.
NOTE : IE can display *multiline tooltip* but Firefox won't.
<span title="line 1 &#10; line 2">*multiline tooltip*</span>

5.12 Have a scrolling display


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0125.html
Use the MARQUEE tag . In this example, the scolling stops when the mouse is over the scrolling
zone.
<marquee direction=up scrollamount=1 scrolldelay=100
onmouseover='this.stop()' onmouseout='this.start()' height=60>
hello world<br>
(IE and FF ok)
<p><a href="http://www.rgagnon.com/howto.html">Real's HowTo</a>
</marquee>

hello world
(IE and FF ok)
Real's HowTo

5.13 Display a page righttoleft


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0127.html
Use the HTML tag
<HTML dir=rtl>

Try it here : js0127rtl.html

5.14 Have a list with colored elements


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0101.html
<html>
<head>
<title></title>

5.12 Have a scrolling display

<style type="text/css">
<!
#opt1{
backgroundcolor:#CCC;
}
#opt2{
backgroundcolor:#FF0;
}
>
</style>
</head>
<body>
<form action="">
<select>
<option id="opt1">Abcde</option>
<option id="opt2">Fghijkl</option>
<option id="opt1">Mnopqr</option>
<option id="opt2">Stuvw</option>
</select>
</form>
</body>
</html>

Try it :

5.15 Prevent printing of a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0067.html
These tips will only make it harder.
[IE]
<BODY onBeforePrint="document.body.style.display = 'none';"
onAfterPrint="document.body.style.display = '';">

or
<STYLE media="print">
BODY {display:none}
</STYLE>

5.16 Validate HTML


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0104.html
You can validate online here and here.
You can download a servlet to validate locally your CSS pages or do it online here.

5.15 Prevent printing of a page

5.17 Fix Netscape "CSS resize bug"


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0065.html
Netscape has the bad habit to move around element around when you resize a window while IE
keep your layout intact. Simply the following code in your page :
// Netscape fix resize bug Ns4
function WM_netscapeCssFix() {
if (document.WM.WM_netscapeCssFix.initWindowWidth !=
window.innerWidth ||
document.WM.WM_netscapeCssFix.initWindowHeight !=
window.innerHeight) {
document.location = document.location;
}
}
function WM_netscapeCssFixCheckIn() {
if ((navigator.appName == 'Netscape')
&(parseInt(navigator.appVersion) == 4)) {
if (typeof document.WM == 'undefined'){
document.WM = new Object;
}
if (typeof document.WM.WM_scaleFont == 'undefined') {
document.WM.WM_netscapeCssFix = new Object;
document.WM.WM_netscapeCssFix.initWindowWidth = window.innerWidth;
document.WM.WM_netscapeCssFix.initWindowHeight = window.innerHeight;
}
window.onresize = WM_netscapeCssFix;
}
}
WM_netscapeCssFixCheckIn();
// catch all errors...
function stopError() {return true;}
window.onerror=stopError;

5.18 Do simple CSS effects


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0064.html
While this HowTo has nothing to do with Javascript, it's cool so here it is ...
Colored Link effect (on a page)
<HTML><HEAD>
<STYLE type="text/css">
<!
A:hover {color:red}
>
</STYLE>
</HEAD><BODY>
<A HREF="">Move over me</A>
</BODY></HTML>

5.17 Fix Netscape "CSS resize bug"

You can try it here.

Colored effect
<span onmouseover="style.color='ff0000';"
onmouseout="style.color='00ff00';">Move over me</span>
You can try it : Move over me

Link with no underline


<a href="../howto.html" style="textdecoration: none">link</a>
You can try it here .

Glow effect (IE only)


<span style="position:relative; width:190; height:10;
filter:glow(Color=#009966,Strength=1)"> Glow effect ! </span>

It looks like his : Glow effect !


Highlighted text
<SPAN STYLE="backgroundcolor:orange">i'm highlighted!</SPAN>
Here how it looks

5.19 Share a stylesheet


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0072.html
Stylesheets are a very useful to share common attributes. An added bonus is when a style sheet
is attached to page to Zoom effect (with the mouse roulette) is disabled so your design is not
affected.
Take the following stylesheet (test.css)
<style type="text/css">
<!
body { fontfamily: Verdana,Arial, Helvetica, sansserif;
fontsize: 10pt}
p { fontfamily: Arial ; fontsize: 10pt }
td { fontfamily: Arial ; fontsize: 12pt }
th { fontfamily: Verdana; fontsize: 10pt }
h1 { fontfamily: Arial; fontsize: 24pt; }
h2 { fontfamily: Times; fontsize: 18pt; }
h3 { fontfamily: Arial; fontsize: 11pt; }
A:link { color:#000000; }
A:visited { color:#336633; }
A:hover { color:#FF0000; }
>
</style>

This stylesheet can be attached to a page with the LINK tag.


<HTML><HEAD>
<TITLE></TITLE>
<LINK TYPE="text/css" HREF="test.css" REL="stylesheet"
TITLE="mystyle">
</HEAD>
<BODY>
<h1> Title h1</h1>

5.19 Share a stylesheet

<h2> Title h2</h2>


<h3> Title h3</h3>
<p>Let's a have a table
<table><th>Table header<tr><td>element 1<td>element2
</tr></table>
</BODY>
</HTML>
If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982005


[ home ]

5.20 Control background image with CSS


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0074.html
NOTE: You place this code in the HEAD section of your page.

Regular
<STYLE>
body
{
backgroundimage:
url(../images/backg.gif)
}
/STYLE
TRY IT HERE.

Tile vertically (repeaty) or horizontally (repeatx)


<STYLE>
body
{
backgroundimage:
url(../images/backg.gif);
backgroundrepeat: repeatx
}
/STYLE
TRY IT HERE.

Center with no repeat


<STYLE>
body
{
backgroundimage:
url(../images/backg.gif);
backgroundrepeat: norepeat;
backgroundposition: center center
}
/STYLE
TRY IT HERE.

Center and no scroll (IE only)


<STYLE>
body
{

5.20 Control background image with CSS

backgroundimage:
url(../images/backg.gif);
backgroundrepeat: norepeat;
backgroundposition: top center;
backgroundattachment: fixed
}
/STYLE
TRY IT HERE.

5.21 Forcing a FormFeed when printing a page


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0075.html
Using StyleSheet, it's easy to force a page break when printing a page.
<table>
<tr><td>Page 1</td></tr>
</table>
<table style="pagebreakbefore: always">
<tr><td>Page 2</td></tr>
</table>

5.22 Browser bugs


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0081.html
Here some good references about known bugs in browser (HTML/CSS).
1. http://css.nu/pointers/bugs.html
2. http://www.webstandards.org/
3. http://www.utoronto.ca/ian/style/cssbugs/home.html
4. http://www.robinlionheart.com/stds/html4/
5. http://www.xs4all.nl/~ppk/js/index.html
6. http://www.hixie.ch/tests/html40/

5.23 Not print the submit button


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0082.html
[CSS]
@media print {
input[type="submit"] { display : none }
}

5.21 Forcing a FormFeed when printing a page

5.24 Blink text


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0098.html
The <BLINK> works only on Netscape browser, IE doesn't support it. One workaround is to use
timer.
<body

onload="setInterval('blinkIt()',500)">

<script type="text/javascript">
function blinkIt() {
if (!document.all) return;
else {
for(i=0;i<document.all.tags('blink').length;i++){
s=document.all.tags('blink')[i];
s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
}
}
}
</script>
<blink>Am i blinking ?</blink>

Here how it looks : Am i blinking ?


You can achive the same effect with some simple CSS but not all browsers will render the
blinking (N7 ok, IE5 no) :
<style>
.super {textdecoration: blink; textalign: center}
</style>
<span class="super">Real's HowTo</span>

Here how it looks : .super {textdecoration: blink; textalign: center} Am i blinking ?

5.25 Have text in bold in a FORM INPUT


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0107.html
<input type="text" style="fontweight:bold;" id="in1" value="foo">

It looks like this

5.26 Use an Image as table cell background


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0116.html
<STYLE style="text/css">
td.special {
backgroundimage: url('../images/line.gif');

5.24 Blink text

backgroundrepeat: repeatx;
backgroundposition: center;
}
</STYLE>
<TABLE border=0>
<TR><TD >line 1 line 1 line 1 line 1 line 1 line 1 line 1</TD></TR>
<TR><TD class='special'>
line 2 line 2 line 2 line 2 line 2 line 2 line 2</TD></TR>
<TR><TD >line 3 line 3 line 3 line 3 line 3 line 3 line 3</TD></TR>
</TABLE>

The output : td.special { backgroundimage: url('../images/line.gif'); backgroundrepeat: repeatx;


backgroundposition: center; }
line 1 line 1 line 1 line 1 line 1 line 1 line 1
line 2 line 2 line 2 line 2 line 2 line 2 line 2
line 3 line 3 line 3 line 3 line 3 line 3 line 3

5.27 Customize button look and feel


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0124.html
Background color
<input type="button" value="hello" size=10
style="backgroundcolor:rgb(235,207,22)">

Change color on mouse over


<input type="button" value="hello" name="B1"
onMouseOut=this.style.color="blue"
onMouseOver=this.style.color="red">

Flat button
<input type="button" value="hello" style="border:1px solid #666666;
height:17px; width:25pt; fontsize:9pt; BACKGROUNDCOLOR: #E8E8FF;
color:#666666">

borderless button
<input type="button" value="hello" style="backgroundcolor:
transparent; border: 0;">

Change the style on mouse over


.style1 { fontsize: 12px; background: #CCCCFF; borderwidth: thin thin thin thin; bordercolor:
#CCCCFF #CCCCCC #CCCCCC #CCCCFF} .style2 { fontsize: 12px; fontweight: bold;
background: #CCFFCC; borderwidth: thin medium medium thin; bordercolor: #CCFF99 #999999
#999999 #CCFF99}
Hello :

5.27 Customize button look and feel

<style type="text/CSS">
.style1 { fontsize: 12px; background: #CCCCFF;
borderwidth: thin thin thin thin;
bordercolor: #CCCCFF #CCCCCC #CCCCCC #CCCCFF}
.style2 { fontsize: 12px; fontweight: bold;
background: #CCFFCC; borderwidth: thin medium medium thin;
bordercolor: #CCFF99 #999999 #999999 #CCFF99}
</style>
<p>Hello :
<input type="submit" name="Submit" value="world"
onmouseover="this.className='style2'"
onmouseout="this.className='style1'" class="style1">

5.28 Embed an image into textfield


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0131.html
This can be useful to give a visual cue for a specific field like a mandatory value.
<style>
input.man { backgroundimage: url(../images/mandatory.gif);
backgroundrepeat: norepeat;
backgroundposition: center left;
paddingleft: 0.5em;
}
</style>
...
<label> Value : <input type=text class=man width=50/></label>

input.man {backgroundimage: url(../images/mandatory.gif); backgroundrepeat:


norepeat;backgroundposition: center left; paddingleft: 0.5em; } It looks like :
Value :
If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982007


[ home ]

5.29 Display the file type as an image on a link


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0132.html
<style>
a[href$='.pdf'] {
display:inlineblock;
paddingright:20px;
lineheight:18px;
background:transparent url(../images/pdf.gif) center right norepeat;
}

5.28 Embed an image into textfield

</style>

It looks like a[href$='.pdf'] { display:inlineblock; paddingright:20px; lineheight:18px;


background:transparent url(../images/pdf.gif) center right norepeat; }
realhowtovbs.pdf
The $ operator means "ends with".
The ^ operator means starts with, so it's possible to detect "http:" or "mailto:" link and display special
icon!
<style>
a[href^="mailto:"] {
display:inlineblock;
paddingright:20px;
background:transparent url(../images/link.jpg) center right norepeat;
}
</style>

It looks like
a[href^="mailto:"] { display:inlineblock; paddingright:20px; background:transparent
url(../images/link.jpg) center right norepeat; } Write to Elvis!
See this interesting article more infos on the subject.
If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982007


[ home ]

5.30 Add comments to CSS


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0141.html
/*
Multiline comments begin with
forward slash and asterisk and end
with an asterisk and forward slash
*/
/* A comment can be on a single line too */

Written and compiled Ral Gagnon 2007 real@rgagnon.com


http://www.rgagnon.com

5.30 Add comments to CSS

6 Form
6.1 jsform

6.2 Cool FORM tips


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0114.html
Here some little known HTML tags to enhance the look and feel of HTML FORM.
The first one is the tag LABEL. This tag is used to attach a label to a component.
If you use something like this :
<FORM>
Name <INPUT TYPE="text" ID="fname" VALUE="">
</FORM>

The result is
Name You need to click in the field to give focus and be able to type something.
If you attach a LABEL to a field then you can click the label (or the field) and then the attached
component will gain the focus.
<FORM>
<LABEL
<INPUT
<BR>
<LABEL
<INPUT
Choose
<INPUT
<LABEL
<INPUT
<LABEL
</FORM>

FOR="tf1">Name </LABEL>
TYPE="text" ID="tf1" VALUE="">
FOR="tf2">Email</LABEL>
TYPE="text" ID="tf2" VALUE=""><br><BR>
<LABEL FOR="rb1">Yes</LABEL> or <LABEL FOR="rb2">No</LABEL>
ID="rb1" NAME="nlrb" TYPE="radio" VALUE="yes">
FOR="rb1"> Yes</LABEL>
ID="rb2" NAME="nlrb" TYPE="radio" VALUE="no">
FOR="rb2">No</LABEL>

You can try it here :


Name (click here)
Email (or here)
Choose Yes or No Yes (click here) No (or here too)
The FIELDSET defines a group of form elements as being logically related. The browser draws a
box around the set of fields to indicate that they are related.
<FORM>
<FIELDSET>

6 Form

Name <INPUT TYPE="text" ID="name" VALUE="">


Email<INPUT TYPE="text" ID="email" VALUE="">
</FIELDSET>
</FORM>

Here how it looks :


Name Email
It is possible to put a title with the tag LEGEND.
<FORM>
<FIELDSET STYLE="width : 45%; ">
<LEGEND>Contact us</LEGEND>
<label for="name2">Name </label>Name <INPUT TYPE="text" ID="name2" VALUE=""> <br>
<label for="email2">Email</label>Email<INPUT TYPE="text" ID="email2" VALUE="">
</FIELDSET>
</FORM>

Here how it looks (with STYLE to limit the width):


Contact us Name
Email
And finally, you can make the SUBMIT button a little less boring...
<STYLE TYPE="text/css">
input.howto {
backgroundcolor: #FFFFCC;
fontweight: bold;
fontsize: 12px;
color: black;}
</STYLE>
<FORM>
<FIELDSET STYLE="width : 45%; ">
<LEGEND><B>Type your query</B></LEGEND>
<LABEL FOR="query">Name </LABEL> <INPUT TYPE="text" ID="query" VALUE="">
<INPUT CLASS="howto" TYPE="submit" VALUE="Submit">
</FIELDSET>
</FORM>

input.howto { backgroundcolor: #FFFFCC; fontweight: bold; fontsize: 12px; color: black;}


Here how it looks :
Type your query Name

6.3 Open a page from a FORM INPUT field


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0016.html
<HTML><HEAD>
<SCRIPT>
function gotoURL(){
var newURL = document.GotoForm.theURL.value

6.3 Open a page from a FORM INPUT field

document.location.href=newURL
}
</SCRIPT></HEAD>
<BODY>
<FORM ACTION="JavaScript:gotoURL()"
METHOD="GET"
NAME="GotoForm">
URL:
<INPUT
TYPE="text"
NAME="theURL"
SIZE="50"
VALUE="http://www.google.com"
MAXLENGTH="100">
<INPUT TYPE="submit"
VALUE="Goto">
</FORM></HTML>

Try it : URL:

6.4 Use multiple submit buttons on one form


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0018.html
<SCRIPT>
function submitFunction(i) {
if (i==1) document.theForm.action=
"http://www.company.com/cgibin/cgi1.cgi";
if (i==2) document.theForm.action=
"http://www.company.com/cgibin/cgi2.cgi";
if (i==3) document.theForm.action=
"http://www.company.com/cgibin/cgi3.cgi";
document.theForm.submit()
}
</SCRIPT>
<FORM NAME="theForm">
<INPUT TYPE="button" VALUE="Submit 1" onClick="submitFunction(1)">
<INPUT TYPE="button" VALUE="Submit 2" onClick="submitFunction(2)">
<INPUT TYPE="button" VALUE="Submit 3" onClick="submitFunction(3)">
</FORM>

6.5 Send the FORM response to another FRAME


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0028.html
To send the result of a FORM request to another FRAME, you provide the FRAME name in the
target property of the FORM. The FRAME name is the one defined by the NAME parameter in the
FRAME declaration. The name must be unique.
[main HTML (a.html)]
<HTML><HEAD></HEAD>
<FRAMESET COLS="50%,*">

6.4 Use multiple submit buttons on one form

<FRAME SRC="f1.html" NAME="f1" >


<FRAME SRC="f2.html" NAME="f2">
</FRAMESET>
</HEAD>

[f1.html]
<HTML><HEAD></HEAD><BODY>
<FORM NAME="tFORM"
METHOD=GET
ACTION="http://www.abc.com/theCGI"
onSubmit="document.tFORM.target = 'f2';return true;"
>
<INPUT TYPE=HIDDEN NAME="n" VALUE="Real Gagnon">
<INPUT TYPE=SUBMIT VALUE="Output to f2 frame">
</FORM></BODY>
</HEAD>
>

Thanks to Amos Bieler for the following tip


Rather than use "document.tFORM.target" you could simply put the "TARGET" attribute in the
FORM tag in the first place.

6.6 Initialize a SELECT "on the fly"


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0033.html
This example initialize a SELECT based on the selection of another one.
<HTML>
<body onload="settopic();">
<SCRIPT>
var javat = new Array(
"Language", "String and Number", "Environment","IO",
"Applet", "Swing", "AWT","Javascript interaction",
"JDBC", "Thread", "Networking", "Servlet/JSP",
"XML", "Internationalization", "Security", "JNI",
"Date and Time", "Open Source", "Varia", "DEPRECATED"
);
var javal = new Array(
"topics/javalanguage.html", "topics/java.stringnumber.html",
"topics/javaenv.html","javaio.html", "topics/javaapplet.html",
"topics/javaswing.html", "topics/javaawt.html","topics/javajs.html",
"topics/javajdbc.html", "topics/javathread.html", "topics/javanet.html",
"topics/javajsp.html", "topics/javaxml.html", "topics/javainter.html",
"topics/javasecurity.html", "topics/javajni.html", "topics/javadate.html",
"topics/javaos.html", "topics/javavaria.html", "topics/javadeprecated.html"
);
var javast = new Array(
"Language", "Form", "Varia"
);

6.6 Initialize a SELECT "on the fly"

var javasl = new Array(


"topics/jslanguage.html", "topics/jsform.html", "topics/jsvaria.html"
);
var pbt = new Array(
"Powerscript", "WinAPI,Registry,COM", "Datawindow", "Database",
"PFC", "Common problems", "Jaguar/EAServer"
);

var pbl = new Array(


"topics/pbpowerscript.html", "topics/pbwinapiregistry.html", "topics/pbdatawindow.html",
"topics/pbdatabase.html", "topics/pbpfc.html", "topics/pbcommon.html", "topics/pbjaguar.
);

function settopic() {
var selectHowTo = document.theForm.howto;
var selectTopic = document.theForm.topic;
var theHowTo = selectHowTo.options[selectHowTo.selectedIndex].value;
if (theHowTo == "java"){
fillTheSelect(selectTopic, javat, javal);
}
if (theHowTo == "js"){
fillTheSelect(selectTopic, javast, javasl);
}
if (theHowTo == "pb"){
fillTheSelect(selectTopic, pbt, pbl);
}
}
function fillTheSelect(theSelect,values,links) {
theSelect.options.length = 0;
for(var i=0; i < values.length; i++) {
theSelect.options[theSelect.options.length] = new Option(values[i], links[i]);
theSelect.options[0].selected = true;
}
}
function go() {
var selectTopic = document.theForm.topic;
var thePage = selectTopic.options[selectTopic.selectedIndex].value;
window.open(thePage, "_top");
}

</SCRIPT>
<FORM NAME="theForm" METHOD="POST">
<table border="0">
<tr><td>
Select HowTo type :
<td><SELECT NAME="howto" onChange="settopic();">
<OPTION VALUE="java" SELECTED>Java HowTo
<OPTION VALUE="js">Javascript HowTo
<OPTION VALUE="pb">Powerbuilder HowTo
</SELECT>
<tr><td>Select the Topic :
<td><SELECT NAME="topic">
<OPTION>

6.6 Initialize a SELECT "on the fly"

<OPTION>
<OPTION>
<OPTION>
<OPTION>
</SELECT>
<input type="button" onclick="go()" value="Go"/>
</table>
</FORM>
</BODY>
</HTML>

Try it :
Select HowTo type :
Select the Topic :

6.7 Suggest a form value


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0078.html
When you click inside the text box, you will see that the text disappears.
<script language="Javascript">
<!
function doClear(theText) {
if (theText.value == theText.defaultValue) {
theText.value = ""
}
}
//>
</script>
<form>
<input type="text" size=15 value="Try it here" onFocus="doClear(this)">
</form>

Or you can keep (and select) the default value :


<script language="Javascript">
<!
function doSelect(theText) {
if (theText.value == theText.defaultValue) {
theText.select();
}
}
//>
</script>
<input type="text" value="Try it here" onfocus="doSelect(this)">

6.8 Restrict input to alphanumeric and uppercase

6.7 Suggest a form value

Current version of this HowTo :


http://www.rgagnon.com/jsdetails/../jsdetails/js0084.html
The first method should work in all browsers but does not prevent pasting from the mouse (onblur
will work though). The second method works in a satisfactory way in IE6.
Method 1<input type="text"
onkeydown="f(this)"
onkeyup="f(this)"
onblur="f(this)"
onclick="f(this)" />
Method 2<input type="text"
onattrmodified="g(this)"
onpropertychange="g(this)" />
<script type="text/javascript">
function f(o){
o.value=o.value.toUpperCase().replace(/([^09AZ])/g,"");
}
function g(o){
if(/[^09AZ]/.test(o.value)){
o.value=o.value.toUpperCase().replace(/([^09AZ])/g,"");
}
}
</SCRIPT>

Try it here
Method 1 Method 2
If you need only to restrict to uppercase then you can apply a specific style, no javascript is needed.
Thanks to RW Anderson for the tip!

<input type="text" style="texttransform: uppercase;" />

Try it here :
An interesting effect is to restrict to lowercase and use a "small caps" font.
<input type="text" style="texttransform: lowercase;fontvariant: smallcaps;" />

Try it here :

6.9 Prevent a FORM SUBMIT with ENTER


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0118.html
To submit the form only when user click the SUBMIT button.
First technique (IE only)

6.9 Prevent a FORM SUBMIT with ENTER

<script>
function noenter() {
return !(window.event &window.event.keyCode == 13);
}
</script>
<form name="myform1" action="http://ww.google.ca">
text1:<input type=text onKeyPress="return noenter()">
text2:<input type=text onKeyPress="return noenter()">
<input type=submit value="GO">
</form>

Try it (IE only): text1: text2:


Second method (works IE and FF)
<form name="myform2" action="http://ww.google.ca" onSubmit="return false">
text1:<input type=text >
text2:<input type=text >
<input type=button value="GO" onClick="document.myform2.submit()">
</form>

Try it (works IE and FF): text1: text2:

6.10 Expand a SELECT with mouse over


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0126.html
<SELECT
onmouseover="this.size=this.length"
onmouseout="this.size=1">
<OPTION>1111
<OPTION>2222
<OPTION>3333
</SELECT>

Try it here :

6.11 Prevent multiple submit


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0110.html
<script>
var submitDone = false;
function submitForm(myForm, button) {
if (!submitDone) {
submitDone = true;
button.value = 'Please Wait';
button.disabled = true;
myForm.submit();
}

6.10 Expand a SELECT with mouse over

else {
alert ("Already submitted, please wait!");
}
return true;
}
</script>
<form name="longsubmit"
action="http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?query=foo">
Impossible to submit multiple times
<input type="button" value="Go"
onClick="return submitForm(document.longsubmit, this)">
/FORM

try it :
Impossible to submit multiple times

6.12 Auto tab in form fields


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0113.html
<script>
function autotab(current,to){
if (current.getAttribute &
current.value.length==current.getAttribute("maxlength")) {
to.focus()
}
}
</script>
<b>Enter your phone number ex (18885551234):</b>
<form name="telephone">
<input type="text" name="phone0"
size=2 onKeyup="autotab(this, document.telephone.phone1)" maxlength=1>
<input type="text" name="phone1"
size=4 onKeyup="autotab(this, document.telephone.phone2)" maxlength=3>
<input type="text" name="phone2"
size=4 onKeyup="autotab(this, document.telephone.phone3)" maxlength=3>
<input type="text" name="phone3" size=5 maxlength=4>
</form>

Try it :
Enter your phone number ex (18885551234):

6.13 Restrict input to alphanumeric and uppercase


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0084.html
The first method should work in all browsers but does not prevent pasting from the mouse (onblur
will work though). The second method works in a satisfactory way in IE6.
Method 1<input type="text"

6.12 Auto tab in form fields

onkeydown="f(this)"
onkeyup="f(this)"
onblur="f(this)"
onclick="f(this)" />
Method 2<input type="text"
onattrmodified="g(this)"
onpropertychange="g(this)" />
<script type="text/javascript">
function f(o){
o.value=o.value.toUpperCase().replace(/([^09AZ])/g,"");
}
function g(o){
if(/[^09AZ]/.test(o.value)){
o.value=o.value.toUpperCase().replace(/([^09AZ])/g,"");
}
}
</SCRIPT>

Try it here
Method 1 Method 2
If you need only to restrict to uppercase then you can apply a specific style, no javascript is needed.
Thanks to RW Anderson for the tip!

<input type="text" style="texttransform: uppercase;" />

Try it here :
An interesting effect is to restrict to lowercase and use a "small caps" font.
<input type="text" style="texttransform: lowercase;fontvariant: smallcaps;" />

Try it here :

6.14 Disable a checkbox


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0080.html
<INPUT TYPE="checkbox" NAME="MyCheckbox" VALUE="Select Me" DISABLED>

or
document.forms[0].MyCheckbox.disabled = false;

If your browser supports this feature, the following checkbox should be disabled.

6.14 Disable a checkbox

6.15 Make a checkbox readonly


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0129.html
With a small javascript function, you can have a good looking readonly checkbox and not use the
greyed disabled look.
<HTML>
<HEAD>
<SCRIPT>
function readOnlyCheckBox() {
return false;
}
</SCRIPT>
<BODY>
<input type="checkbox" id="cbx1"
` onClick="return readOnlyCheckBox()" CHECKED /> readonly
<br/>
<input type="checkbox" id="cbx2"
CHECKED DISABLED/> disabled
</BODY>
</HTML>

It looks like this : readonly disabled


If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982007


[ home ]

6.16 Preload images and change them with a SELECT


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0057.html
<HTML><HEAD><SCRIPT>
// preload images
var img1 = new Image().src = "../images/jht.gif"
var img2 = new Image().src = "../images/jsht.gif"
var img3 = new Image().src = "../images/pht.gif"
function setImage(imageSelect) {
theImageIndex = imageSelect.options[imageSelect.selectedIndex].value;
if (document.images)
document.images[0].src = eval("img" + theImageIndex);
}
</SCRIPT></HEAD><BODY>
<FORM NAME="theForm" METHOD="POST">
<TABLE><TR><TD>Images: <TD>
<SELECT NAME="items" onChange="setImage(this)">
<OPTION VALUE="1">Java Howto
<OPTION VALUE="2">Javascript Howto
<OPTION VALUE="3">Powerbuilder Howto
</SELECT>
<TD><IMG SRC = "../images/jht.gif" HEIGHT=100 WIDTH=200>

6.15 Make a checkbox readonly

</TABLE></FORM></BODY></HTML>

You can try it here


NOTE : Preloading is possible without using Javascript.
<style type="text/css">
preload {display:none;}
</style>
<img src="../images/jht.gif"
alt="java how to" title="java how to" class="preload">
<img src="../images/jsht.gif"
alt="javascript how to" title="javascript how to" class="preload">
<img src="../images/pht.gif"
alt="powerbuilder how to" title="powerbuilder how to" class="preload">
If you find this article useful, consider
making a small donation
to show your supportfor this Web site
and its content.

Written and compiled by Ral Gagnon 19982005


[ home ]

6.17 Select/Unselect text in TextArea with a MouseOver


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0059.html
When the mouse is over the textarea, "your comment" is selected. If the user starts typing,
"comment here" is erased. The DIV is for IE, LAYER is for Netscape.
<SCRIPT>
function changeSelect(flag) {
if (flag == 1) {
if (document.theForm.comments.value ==
document.theForm.comments.defaultValue) {
document.theForm.comments.select();
}
}
if (flag == 2) {
document.theForm.comments.value =
document.theForm.comments.value;
}
}
</SCRIPT>
<P>
<DIV onMouseOver="changeSelect(1);"
onMouseOut="changeSelect(2);">
<LAYER onMouseOver="changeSelect(1);"
onMouseOut="changeSelect(2);">
<FORM name="theForm">
<TEXTAREA NAME="comments"
COLS="30" ROWS="4">Your comments</TEXTAREA>
</FORM>
</LAYER>
</DIV>
</P>

6.17 Select/Unselect text in TextArea with a MouseOver

Try it:

6.18 Turn off the "autocomplete" feature of the browser


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0134.html
Modern browsers include a feature called AutoComplete that keeps track of information that you've
recently typed, such as Web site addresses, information in forms, and search queries. As you type
new information, AutoComplete tries to anticipate what you are typing and offers possible matches.
If you don't want the browser to remember previous typed data then you can set the attribute
autocomplete to "off".
<form>
<input type"text" name="username" autocomplete="off">
<form>

You can disable this functionality completely at the browser level, see IE, Firefox

6.19 Limit a textarea to a maximum length


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0091.html
First technique, you validate on the submit the textarea length and return false if too long.
<SCRIPT LANGUAGE="JAVASCRIPT">
function checkLength(form){
if (form.description.value.length > 20){
alert("Text too long. Must be 20 characters or less");
return false;
}
return true;
}
</SCRIPT>
<FORM ACTION="..." METHOD="..." onSubmit="return checkLength(this)">

Second technique, as you typed, the length is checked. If the input is too long then it is truncated.
<script>
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</script>
<form name="myform">
textarea limit 20 chars :<br>
<textarea rows="5" cols="30" onKeyDown="limitText(this,20);"
onKeyUp="limitText(this,20);">
</textarea><br>

6.18 Turn off the "autocomplete" feature of the browser

</form>

textarea limit 20 chars :


thanks to wsperry for the tip

6.20 Check for "letteronly" INPUT


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0133.html
To check for regular ASCII (no accent)
<script>
function validate(strValue) {
var objRegExp = /^[az]+$/;
return objRegExp.test(strValue);
}
</script>

A more friendly approach is to accept accented letters too!


<script>
function validate(strValue) {
var objRegExp = /^[az\u00C0\u00ff]+$/;
return objRegExp.test(strValue);
}

Try it here : If you want to accept a space then


var objRegExp

= /^[az\u00C0\u00ff\s]+$/;

6.21 Disable/Enable a FORM


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0139.html
<html>
<script type="text/javascript">
function grayer(formId, yesNo) {
var f = document.getElementById(formId), s,
s = f.style;
opacity = yesNo? '40' : '100';
s.opacity = s.MozOpacity = s.KhtmlOpacity =
s.filter = 'alpha(opacity='+opacity+')';
for(var i=0; i<f.length; i++) f[i].disabled
}
window.onload=function(){grayer('f_1',true);};
</script>
<style type="text/css">
form { _height: 1%; /* hack IE */

6.20 Check for "letteronly" INPUT

opacity;

opacity/100;
= yesNo;
// disabled by default

padding: 10px; background:#ff5;


}
</style>
<body>
<button onclick="grayer('f_1',false);">
Enable Form 1</button>
<button onclick="grayer('f_1',true);">
Disable Form 1</button>
<p>
<form id="f_1" action="#" onsubmit="return false;">
<p>Form 1 : <input name="test" type="text"> <input type="submit">
</form>
</body>
</html>

Try it here :
Form 1 :

6.22 Nice "focus" effect in a FORM field


Current version of this HowTo :
http://www.rgagnon.com/jsdetails/../jsdetails/js0140.html
In CSS, the :focus pseudoclass can be used to apply styles to a page element that receives focus.
IE doesn't recognise this at all, you need add the style "manually".
In this HowTo, the special javascript function to init the style is called (from the BODY onLoad) only
if the browser is IE.
<html>
<head>
<script>
function initie() {
//
// called from the BODY onLoad with IE only.
// for mozillabased browser only the CSS is used.
//
var i = 0;
// get all the forms
var f = document.forms[i];
while (f) {
//alert(f.name);
// get all elements of the current form
var elem = document.forms[i].elements;
for (var i = 0; i < elem.length; i++) {
// make a reference to our style
elem[i].onfocus = function() {
this.className += ' focusie';
}
elem[i].onblur = function() {

6.22 Nice "focus" effect in a FORM field

this.className = this.className.replace('focusie', '');


}
}
// next form if any
f = document.forms[++i];
}
}
</script>
<style>
/* mozilla */
input:focus, textarea:focus {
backgroundcolor: lightblue;
}
/* ie */
input.focusie, textarea.focusie {
backgroundcolor: lightblue;
}
</style>
</head>
<![if IE]>
<body onload="initie();">
<![endif]>
<![if !IE]> <>
<body>
<!> <![endif]>
<form name='test'>
<LABEL FOR="tf1">Name </LABEL><br>
<input id="tf1" type="text" size="40">
<p>
<LABEL FOR="tf2">Email </LABEL><br>
<input id="tf2" type="text" size="40">
<p>
<LABEL FOR="tf3">Comments </LABEL><br>
<textarea id="tf3" rows="5" name="comments" cols="45" wrap="virtual"></textarea></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>

Try it here :
Name
Email
Comments

Written and compiled Ral Gagnon 2007 real@rgagnon.com


http://www.rgagnon.com

6.22 Nice "focus" effect in a FORM field

You might also like