Realhowto Javascript
Realhowto Javascript
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
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
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
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".
output :
To show in an alert box with accented characters, use something like this :
alert("\350 \351 \352 \353 ");
Try it here
1 Language
}
</SCRIPT>
Try it here :
Try it :
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();
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();">
Try it :
") dlg.document.write ("
1.10 ",msg,"
") dlg.document.write ("
") dlg.document.write ("") dlg.document.write ("
") 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
<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")');
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
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>
= '#C0C0C0'"
= '#FFFFFF'"
= '#C0C0C0'"
= '#FFFFFF'"
= '#C0C0C0'"
= '#FFFFFF'"
= '#C0C0C0'"
= '#FFFFFF'"
Statistics
1930
1933
1934
1935
Detroit
Detroit
Detroit
Detroit
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>
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
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();
}
}
Then in javascript
document.JavaBeep.oneBeep();
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();
</script>
</head><body></body></html>
Try it here.
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);
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);
For Netscape 6
<HTML><HEAD>
Try it here
See also this related HowTo.
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
You can save / restore the body and not the whole document by using
document.all("content").innerHTML
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.
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>
onClick="openMyPage();"
VALUE="open MyPage">
</FORM></BODY></HTML>
<A HREF="javascript:myFunction()">
Click here for Javascript action!</A>
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>
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%";
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.
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>
<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>
Some browsers may support a special parameter in the BODY tag to disable the RMB
<BODY oncontextmenu="return false">
[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>
<SCRIPT LANGUAGE="JavaScript">
var myarray = new
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')">
[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.
function URLencode(sStr) {
return escape(sStr)
.replace(/\+/g, '%2B')
.replace(/\"/g,'%22')
.replace(/\'/g, '%27');
}
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 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>
alert("equals");
}
Not casesensitve:
if (aString.toUpperCase() == anotherString.toUpperCase()) {
alert("equals");
}
return r;
}
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
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);
}
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)) {
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
USAGE:
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
Z5Z5Z5 orZ5Z5Z5
Time
/^([19]|1[02]):[05]\d(:[05]\d(\.\d{1,3})?)?$/
999999999 or999999999
3 Common expressions
*
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
4 Varia
4.1 jsvaria
4 Varia
}
//>
</SCRIPT>
"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();">
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
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>
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.
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>
</BODY></HTML>
if (document.all)
window.external.AddFavorite(bookmarkurl,bookmarktitle)
}
>
</script>
<a href="javascript:addbookmark()">Add Real's HowTo to your Bookmarks</a>
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
if (useAcrobat)
document.write("Acrobat reader ok");
else
document.write("Acrobat reader not found");
//>
</SCRIPT>
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.
try it here
Want to know what is going on ?
See these XBM related sites : Site 1 and Site 2
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
Search
If you want sophisticated tooltip then take a look at the overLib javascript library at
http://www.bosrup.com/web/overlib/.
<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.
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.
NOTE: Works on IE but... on Firefox a setting can disable the ability for a script to block the
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
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>
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]
];
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.
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'
+ '&cht=bhs'
+ '&chco=ff0000'
+ '&chd=t:');
for (var i=0; i < data.length; ++i) {
document.write(data[i][1]);
if (i < data.length1) document.write(",");
}
document.write('&chxt=y,x'); // left , bottom
document.write('&chxl=0:|');
for (var i=data.length1; i >= 0 ; i) {
document.write(data[i][0]);
if (i > 0) document.write("|");
}
document.write('&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 & in place of an ampersand (&).
See this HowTo to generate a bar chart using plain Javascript.
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
ref : http://msdn.microsoft.com/enus/library/cc817570.aspx
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>
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.
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>
Real's
<BUTTON><FONT COLOR="#ff0000"><B>Real's<BR>Howto</B></FONT></BUTTON>
Or with an image
<span style=
"backgroundimage:
url('images/realhowto.gif'); backgroundrepeat: norepeat;">
<img src="images/transparent.gif" width="16" height=16"
border="0" alt="RealHowTo">
</span>
Try it here
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.
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>
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>
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 line 2">*multiline tooltip*</span>
hello world
(IE and FF ok)
Real's HowTo
<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 :
or
<STYLE media="print">
BODY {display:none}
</STYLE>
Colored effect
<span onmouseover="style.color='ff0000';"
onmouseout="style.color='00ff00';">Move over me</span>
You can try it : Move over me
Regular
<STYLE>
body
{
backgroundimage:
url(../images/backg.gif)
}
/STYLE
TRY IT HERE.
backgroundimage:
url(../images/backg.gif);
backgroundrepeat: norepeat;
backgroundposition: top center;
backgroundattachment: fixed
}
/STYLE
TRY IT HERE.
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>
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>
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;">
<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">
</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.
6 Form
6.1 jsform
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>
6 Form
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:
[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>
>
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>
<OPTION>
<OPTION>
<OPTION>
<OPTION>
</SELECT>
<input type="button" onclick="go()" value="Go"/>
</table>
</FORM>
</BODY>
</HTML>
Try it :
Select HowTo type :
Select the Topic :
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!
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 :
<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 here :
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
Try it :
Enter your phone number ex (18885551234):
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!
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 :
or
document.forms[0].MyCheckbox.disabled = false;
If your browser supports this feature, the following checkbox should be disabled.
</TABLE></FORM></BODY></HTML>
Try it:
You can disable this functionality completely at the browser level, see IE, Firefox
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>
</form>
= /^[az\u00C0\u00ff\s]+$/;
opacity;
opacity/100;
= yesNo;
// disabled by default
Try it here :
Form 1 :
Try it here :
Name
Email
Comments