Please select a category and click GO
UK Residents: Get great deals on high quality designer bathroom fittings from plumbfit.com

Plumbfit: Basin mixers, showers, taps, towel radiators Plumbfit: Bathroom showers, taps, towel radiators Plumbfit: Bathroom taps, showers, taps, towel radiators Plumbfit: Concealed showers, taps, towel radiators Plumbfit: Exposed showers, taps, towel radiators Plumbfit: Towel rails, showers, taps, towel radiators



It was once rumored that Pokerstars were going to be setting up a vBulletin forum where they would allow different players from around the world to discuss strategies with team Pokerstars.

Go Back Community for Webmasters & Developers > FAQ > The Forum FAQ > Client-Side Technologies FAQ > JavaScript FAQ
Reload this Page Miscellaneous FAQ
Home Register FAQ Members List Calendar Search Today's Posts Mark Forums Read
Search FAQ Search FAQ
Search Word(s):

Matching Options:

Search in:

Use multiple functions in event handlers
There are two ways of accomplishing this. You can place all the functions inside the command like this (using onmouseover attribute and the body tags as a examples):
<a href="#" onmouseover="func1();func2();">link text</a>"

<body onload="func1();func2();">
You can also use a single function to call two other functions:
<script type="text/javascript">
//<![CDATA[
function doBoth()
{
func1();
func2();
}


function func1(){alert("Function 1");}
function func2(){alert("Function 2");}

//]]>
</script>
Then call the doBoth() function in your event handler:
<a href="#" onmouseover="doBoth();">Try it here</a>

<body onload="doBoth();">
Try it here

Stack overflow error message
You have a loop in your script and are running out of memory when running it. Be very careful when debugging - if you insert an alert(); in the wrong place you'll end up rebooting your machine!

Null or not an object error message
The four common reasons for a 'null or not an object' error message are:
  1. misspelling/typo
  2. accessing an object before it is declared
  3. accessing an object that is never declared/defined
  4. accessing the wrong object
1) misspelling/typo:

Remember, javascript is case-sensitive, so myForm and MyForm are not the same thing.

2) accessing an object before it is declared:

All objects must be declared (and usually defined with a value) before they can be accessed. So if you must say something like:
<script type="text/javascript">
//<![CDATA[
   document.myForm.myText.value = 'hello';
//]]>
</script>
<body>
   <form name="myForm">
      <input type="text" name="myText">
   </form>

</body>
it will throw an error. To fix it, make sure it is either inside a function or executed after the HTML is loaded.

For example:
<script language="javascript">
   function doit() {
      document.myForm.myText.value = 'hello';
   }
//]]>
</script>
<body onLoad='doit()'>
   <form name="myForm">
      <input type="text" name="myText">
   </form>
Or,
<body>
   <form name="myForm">
      <input type="text" name="myText">
   </form>
<script type="text/javascript">
//<![CDATA[
   document.myForm.myText.value = 'hello';
//]]>
</script>
3) accessing an object that is never declared/defined:

If you are accessing an object through a loop, remember that html and javascript begin counting with zero (0). So, the following array and loop:
var myArray = new Array(1,2,3);
    for (i = 0; i <= myArray.length; i++)
       alert(myArray[i]);
will cause an error because there is no 'myArray[3]'. To fix it, the loop should look something like this:
for (i = 0; i < myArray.length; i++)
   alert(myArray[i]);
4) accessing the wrong object:

Although the following is not an error, it will cause loss of hair and time. Remember, computers are easily confused, so do not use keywords/reserved words (name, form, select, etc) as variable names. The following will perform as expected -- by the computer, but unfortunately not by you:
<script type="text/javascript">
//<![CDATA[
   var window.name = 'winName';
   function doit(name)
   {
     alert(name)
   }
//]]>
</script>
<form>
   <input type="text" name="name" onBlur="doit(this.name)">
</form>
You might also want to check out this thread.

Password protect a page with JavaScript
JavaScript password protection is commonly insecure and therefore often ineffective.

If you are protecting anything important, you should pursue another option such as a server-side language or the use of an .htaccess file.

If you want to look for some JavaScripts for password protection, try this link: http://javascript.internet.com/passwords/

Make a Print This Page button
Place this function in your page:
<script type="text/javascript">
//<![CDATA[
function printit(){
if (window.print) 
  window.print() ;
else if (document.all) {
        var WebBrowser = 'CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2">'; 
        document.body.insertAdjacentHTML('beforeEnd', WebBrowser); 
        WebBrowser1.ExecWB(6, 6); //Use a 1 vs. a 6 for a prompting dialog box 
        WebBrowser1.outerHTML = "";
     }
}
//]]>
</script>
Be sure the var WebBrowser ... all goes on a single line. Then call it with a button or link:
<a href="#" onclick="printit();return false">Print this page</a>
Print this page

Read or write CSS values with JavaScript
You can access css style properties via an object's style attribute:
object.style.styleattribute = value;
The object would be an HTML element such as "<div>". The style attribute would be the script version of the attribute name, e.g., backgroundImage or borderTopColor. This part is actually easier than it looks if you remember a general rule: the attribute name must have any hyphens removed and the letter following the hyphen must be in upper case; so line-height becomes lineHeight, scrollbar-3dlight-color becomes scrollbar3dLightColor, etc

So now we get:
document.getElementById("thistag").style.backgroundImage = value;
The value for a background image is url(imageaddress), so this must be passed as a string:
document.getElementById("thistag").style.backgroundImage = "url(http://www.webxpertz.net/faqs/jsfaq/misc/images/mybackground.gif)";
Try it by putting your mouse here

Hexadecimal to Decimal and Decimal to Hexadecimal conversion
How do I convert from Decimal to Hexidecimal?
How do I convert from Hexidecimal to Decimal?

Like this:
function hex(n) {var h=parseInt(n).toString(16); return (h.length%2)?"0"+h:h}

function dec(n) {return parseInt(n,16);}

Detect the mouse position
This is cross-browser compatible from NS4 and IE4 upwards.
<html>
<head>
	<title> Position </title>
</head>

<body>

<script type="text/javascript">
//<![CDATA[
//tell Netscape to catch mouse movements
if (document.layers) document.captureEvents(Event.MOUSEMOVE)
//when you detect a mouse movement, do this function
document.onmousemove = chasecur;

//id of the div to play with
var chasediv="myarea";


function chasecur(ns) {
	var X = 0;
	var Y = 0;

//grab the coordinates 
	if (document.all) { 
		X = event.clientX + document.body.scrollLeft;
		Y = event.clientY + document.body.scrollTop;
	}
	else{
		X = ns.pageX;
		Y = ns.pageY;
	}

//grab the div and move it where you want it
	thisthing=getthing(chasediv);
	thisthing.left = X+10;
	thisthing.top  = Y;
//put the coordinates into the div
	content(chasediv,"Pos: x="+X+", y="+Y);
	return true;
}

function getthing(which){
//if it's Internet Explorer, grab it using the "all" collection
	if (document.all) 
		return document.all(which).style;  
	else if (document.getElementById) 
//if it's Netscape 6+, grab it using the DOM function
		return document.getElementById(which).style;  
//if it's Netscape 4, grab it from the Layers
	else if (document.layers) 
		return document.layers[which];  
}

function content(which,what){
	var x;
//if it's Netscape 4, write the value into the Layer's document
	if (document.layers){
		x = document.layers[which].document;
		x.open();
		x.write(what);
		x.close();
	}
	else {
//if it's Netscape or IE 6+, change the content of the DIV
		if (document.all) 
			x = document.all(which);
		else 
			x= document.getElementById(which);
		x.innerHTML = what;
	}
}

//]]>
</script>
<div id="myarea" style='position:absolute;top:0px;left:0px'> </div>
</body>
</html>

Prevent left-clicking of a download link
This will block a download link from being opened with a left-click, forcing viewers to right-click and save the target file to disk or open in another window:
<a href="something.zyx" onclick="alert('Message of your choice');return false">Get something Here</a>

Remove the dotted line around a link
Remove the focus from the link as soon as it receives it:
<a href="url" onfocus="this.blur()" ">Text</a>
Tab to this link:

Make a link that will act like the browser back button
This can be accomplished with:
<a href="javascript:history.go(-1)">Go Back</a>

Make a page that can only be accessed from one of my links
All you need to do is check the document.referrer - the easiest way to do this is with a reqular expression. The following example will only allow you to see the page from a link from a webxpertz.net site:

Set the target attribute for a link in XHTML
Under XHTML strict, the target attribute for a link (or anchor) element is not recognised and thus will not validate. It is, however, still a part of the XHTML DOM and can be set via script, either singly or en masse:
<a href="http://google.com" onclick="this.target='_blank'">Go to Google</a>
or:
<script type="text/javascript">
//<![CDATA[
 function setTarget(){
  var a = document.getElementsByTagName("a");
  for(var i = 0;i < a.length;i++){
   a[i].target = "_blank";
  }
 }
//]]>
onload=setTarget;
</script>

How to dynamically create web-safe hex-codes
This script is courtesy of Roland Alfonso
<script type="text/javascript">
//<![CDATA[
  /* 'rgb'(default)|'hex' */
  function getWebsafe(form) {
    var colours = [];
    var toHex   = form=='#';
    var C = toHex
          ? ['00','33','66','99','cc','ff']
          : ['00','51','102','153','204','255'];
    var k = 216, f = Math.floor;
    if(toHex) while(k--) colours[k]='#'+C[f(k/36)%6]+C[f(k/6)%6]+C[k%6];
    else      while(k--) colours[k]='rgb('+C[f(k/36)%6]+','+C[f(k/6)%6]+','+C[k%6]+')';
    return colours;
  }

  // Just does #hex
  function getHex216(){
    var colours = [];
    var hex     = ['00','33','66','99','cc','ff'];
    var k       = 216, f = Math.floor;
    while(k--) colours[k] = '#'+hex[f(k/36)%6]+hex[f(k/6)%6]+hex[k%6];
    return colours;
  }

  String.prototype.toCSSColor = function(form){
    var S,I = parseInt,hex,isHexForm=this.length<8;
    // to rgb(,,) form //
    if(form!='#'){
      if(!isHexForm) return this+'';
      // conv. #abc to #aabbcc
      var S = ( this.length>4 ? this:this.replace(/\w/g,'$&$&') ).match(/\w{2}/g);
      return 'rgb('+I(S[0],16)+','+I(S[1],16)+','+I(S[2],16)+')';
    } else {      // to #hex form //
      if(isHexForm) return this+'';
      var S = this.match(/\d+/g);
      return ('#'+hx(S[0])+hx(S[1])+hx(S[2])).toUpperCase();
    }

    function hx(sDec){ // conv. decStr to hexStr; (?) add leading 0 ;
        return(hex=I(sDec).toString(16)).length==1? 0+hex:hex;
    }
  }

  /*-----------------------------------------------------------------------
    NOTES: String.prototype.toCSSColor
    
    - Not case-sensitive
    - #abc form accepted
    - ! '#abc'.toCSSColor('#') --> '#abc' (no conversion to #aabbcc)
    - ! No error checking
    - ! Doesn't accept colorNames (yet)
    hex  = '#0033FF'
    sHex = '#03F'
    dec  = 'rgb(0,51,255)'

    hex.toCSSColor()     -->
    sHex.toCSSColor()    -->
    dec.toCSSColor()     --> 'rgb(0,51,255)'

    dec.toCSSColor('#')  -->
    sHex.toCSSColor('#') -->
    hex.toCSSColor('#')  --> '#0033FF'
  -----------------------------------------------------------------------
  */
//]]>
</script>


All times are GMT +1. The time now is 04:28 AM.


Powered by vBulletin® Version 3.6.4
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Copyright ©2002 - 2010, WebXpertz.com. All Rights Reserved.