Computer Forums

Computer Forums (http://www.geekboards.com/forums/index.php)
-   Building Websites (http://www.geekboards.com/forums/forumdisplay.php?f=3)
-   -   JavaScript codes for Web DEV (http://www.geekboards.com/forums/showthread.php?t=15045)

JavaScriptBank 01-28-2011 10:15 AM

Browser Cookie with JavaScript and jQuery
 
This short JavaScript article tutorial guides you how to work with browser cookie, cookie in JavaScript by using the JavaScript framework jQuery, through some basi... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup







JavaScriptBank 01-28-2011 07:49 PM

JavaScript Color Gradient Maker
 
With this JavaScript code example, you can easy make CSS gradient background, [URL="http://www.javascriptbank.com/=JavaScript color gradient"]JavaScript color gradient</a... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Joseph Myers | http://www.codelib.net/
// This script downloaded from www.JavaScriptBank.com

function colorscale(hexstr, scalefactor) {
/* declared variables first, in order;
  afterwards, undeclared local variables */
  var r = scalefactor;
  var a, i;
  if (r < 0 || typeof(hexstr) != 'string')
    return hexstr;
    hexstr = hexstr.replace(/[^0-9a-f]+/ig, '');
    if (hexstr.length == 3) {
    a = hexstr.split('');
  } else if (hexstr.length == 6) {
    a = hexstr.match(/(\w{2})/g);
  } else
    return hexstr;
  for (i=0; i<a.length; i++) {
    if (a[i].length == 2)
      a[i] = parseInt(a[i], 16);
    else {
      a[i] = parseInt(a[i], 16);
      a[i] = a[i]*16 + a[i];
  }
}

var maxColor = parseInt('ff', 16);

function relsize(a) {
  if (a == maxColor)
  return Infinity;
  return a/(maxColor-a);
}

function relsizeinv(y) {
  if (y == Infinity)
  return maxColor;
  return maxColor*y/(1+y);
}

for (i=0; i<a.length; i++) {
  a[i] = relsizeinv(relsize(a[i])*r);
  a[i] = Math.floor(a[i]).toString(16);
  if (a[i].length == 1)
  a[i] = '0' + a[i];
}
return a.join('');
}

function showrainbow(f) {
  var colorcell, hex, i, nhex;
  hex = f.orig.value;
  hex = hex.replace(/\W/g, '');
  nhex = colorscale(hex, f.scalef.value-0);
  if (nhex != hex) {
    f.outp.value = nhex;
    colorcell = document.getElementById('origcolor');
    i = document.getElementById('newcolor');
    colorcell.style.background = '#' + hex;
    i.style.background = '#' + nhex;
    for (i=0; i<256; i++) {
      colorcell = document.getElementById('colorcell'+i);
      nhex = colorscale(hex, i/(256-i));
      colorcell.style.background = '#' + nhex;
      colorcell.nhexvalue = nhex;
    }
  }
}
</script>

Step 2: Copy & Paste HTML code below in your BODY section
HTML
Code:

<div style="width: 400px;">
<form>
<p>
Original color: <input type="text" name="orig" value="339990"><br>
Scale factor: <input type="text" name="scalef" value="4"><br>
<input type="button" value="Output" onclick="showrainbow(this.form)">
<input type="text" readonly name="outp" style="border: none;">
</p>
</form>

<table width="150">
<tr>
<td width="50%" height="50" id="origcolor">Original</td>
<td width="50%" id="newcolor">New</td></tr>
</table>

<table cellpadding="0" cellspacing="0">
<tr>
<script type="text/javascript">
for (i=0; i<256; i++)
document.write('<td width="10" height="50" id="colorcell', i, '" onclick="document.forms[0].outp.value = this.nhexvalue"></td>');
</script>
</tr>
</table>

</div>







JavaScriptBank 01-28-2011 08:24 PM

Built-in JavaScript RegEx APIs
 
Regular Expressions (RegEx) skills are the indispensable knowledges if you would like become a professional JavaScript coder particularly, or a professional programmer generally; because of a lot of p... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup







JavaScriptBank 02-04-2011 07:09 PM

JavaScript OOP with Input Display Toggle
 
Usage of this JavaScript code effect is just toggle (show/display) the input text fields when the users click the specified input checkboxes. But this JavaScript code example made with OOP skills, it'... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Place JavaScript below in your HEAD section
JavaScript
Code:

<script type="text/javascript">
// Created by: Fang | http://www.webdeveloper.com/forum/showthread.php?p=872326#post872326
// This script downloaded from www.JavaScriptBank.com

function addElement() {
var aInput=document.getElementById('myspan').getElementsByTagName('input');
for(var i=0; i<aInput.length; i++) {
    aInput[i].onclick=new Function('addDelete(this)');
    }
}

function addDelete(obj) {
var parentSpan=document.getElementById('myspan');
if(obj.nextSibling.nodeName!='INPUT') { // add
    var oInputText=document.createElement('input');
    oInputText.setAttribute('type', 'text');
    parentSpan.insertBefore(oInputText, obj.nextSibling);
    }
else { // delete
    parentSpan.removeChild(obj.nextSibling);
    }
}

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
  addElement();
});
</script>

Step 2: Copy & Paste HTML code below in your BODY section
HTML
Code:

<span id="myspan">
  <input type="checkbox">

  <input type="checkbox">
  <input type="checkbox">
</span>







JavaScriptBank 02-04-2011 08:58 PM

50+ Great Web Applications of Data Visualization
 
Perhaps just read technical JavaScript article tutorials on jsB@nk made you become humdrum?! Today together, we should change the subject in this post, we'll enjoy 5... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup







JavaScriptBank 02-04-2011 09:33 PM

JavaScript Text Auto-Select onClick
 
If this JavaScript code example installed on a web page, when users click on text-container HTML elements then it will select all of its inner text automatically.

At present, this JavaScript code m... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Place JavaScript below in your HEAD section
JavaScript
Code:

<script type="text/javascript">
// Created by: Matt Murphy | http://www.matts411.com/
// This script downloaded from www.JavaScriptBank.com

function autoSelect(selectTarget) {
        if(selectTarget != null && ((selectTarget.childNodes.length == 1
      && selectTarget.childNodes[0].nodeName == "#text") || (selectTarget.tagName == "INPUT"
      && selectTarget.type == "text"))) {
                  if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
                          selectTarget.select();
                  } else if(window.getSelection) { // FF, Safari, Opera
                          var sel = window.getSelection();
                          var range = document.createRange();
                          range.selectNode(selectTarget.firstChild);
                          sel.removeAllRanges();
                          sel.addRange(range);
                  } else { // IE
                          document.selection.empty();
                          var range = document.body.createTextRange();
                          range.moveToElementText(selectTarget);
                          range.select();
                  }
        }
}
</script>

Step 2: Copy & Paste HTML code below in your BODY section
HTML
Code:

<h4 style="margin-bottom: 0;">A <code>div</code> Element:</h4>

<div onclick="autoSelect(this);">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam ultrices vestibulum elit. Mauris congue sapien sed dolor. Pellentesque sem augue, porttitor id, placerat ac, congue ac, eros. Etiam fermentum consectetuer pede. Donec tincidunt. Suspendisse non nisi. In hac habitasse platea dictumst. In hac habitasse platea dictumst. Integer porta egestas sapien.
</div>

<h4 style="margin-bottom: 0;">An <code>input</code> Element:</h4>
<input type="text" size="50" onclick="autoSelect(this);" value="Lorem ipsum dolor sit amet, consectetuer adipiscing elit.">

<h4 style="margin-bottom: 0;">A <code>textarea</code> Element:</h4>
<textarea rows="5" cols="30" onclick="autoSelect(this);">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam ultrices vestibulum elit. Mauris congue sapien sed dolor. Pellentesque sem augue, porttitor id, placerat ac, congue ac, eros. Etiam fermentum consectetuer pede.

</textarea>

<h4 style="margin-bottom: 0;">A <code>pre</code> Element:</h4>
<pre onclick="autoSelect(this);">
function toggle_visibility(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'none')
    e.style.display = 'block';
  else
    e.style.display = 'none';
}
</pre>







JavaScriptBank 02-04-2011 10:06 PM

Use jQuery to Generate Random Strings
 
This short JavaScript article tutorial guides us how to make a random string with JavaScript (random string JavaScript) and jQuery. Both two detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup







JavaScriptBank 02-04-2011 10:38 PM

Picture Gallery with Display Switcher
 
This is really very cool and amazing picture gallery to promote your personal/business pictures on the web. With two type of displaying, this JavaScript gallery script allow users to switch the layout... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: CSS below for styling thescript, place it into HEAD section
CSS
Code:

<style type="text/css">
body {
        margin: 0;
        padding: 50px 0 0;
        font: 10px normal Verdana, Arial, Helvetica, sans-serif;
        color: #fff;
}
* {
        margin: 0;
        padding: 0;
}

img {
        border: none;
}
h1 {
        font: 5em normal Georgia, 'Times New Roman', Times, serif;
        text-align:center;
        margin-bottom: 20px;
}
h1 span {        color: #e7ff61; }
h1 small{
        font: 0.2em normal Verdana, Arial, Helvetica, sans-serif;
        text-transform:uppercase;
        letter-spacing: 1.5em;
        display: block;
        color: #ccc;
}

.container {
        width: 758px;
        margin: 0 auto;
        padding-bottom: 100px;
        overflow: hidden;
}
ul.display {
        float: left;
        width: 756px;
        margin: 0;
        padding: 0;
        list-style: none;
        border-top: 1px solid #333;
        border-right: 1px solid #333;
        background: #222;
}
ul.display li {
        float: left;
        width: 754px;
        padding: 10px 0;
        margin: 0;
        border-top: 1px solid #111;
        border-right: 1px solid #111;
        border-bottom: 1px solid #333;
        border-left: 1px solid #333;
}
ul.display li a {
        color: #e7ff61;
        text-decoration: none;
}
ul.display li .content_block {
        padding: 0 10px;
}
ul.display li .content_block h2 {
        margin: 0;
        padding: 5px;
        font-weight: normal;
        font-size: 1.7em;

}
ul.display li .content_block p {
        margin: 0;
        padding: 5px 5px 5px 245px;
        font-size: 1.2em;
}
ul.display li .content_block a img{
        padding: 5px;
        border: 2px solid #ccc;
        background: #fff;
        margin: 0 15px 0 0;
        float: left;
}

ul.thumb_view li{
        width: 250px;
}
ul.thumb_view li h2 {
        display: inline;
}
ul.thumb_view li p{
        display: none;
}
ul.thumb_view li .content_block a img {
        margin: 0 0 10px;
}


a.switch_thumb {
        width: 122px;
        height: 26px;
        line-height: 26px;
        padding: 0;
        margin: 10px 0;
        display: block;
        background: url(switch.gif) no-repeat;
        outline: none;
        text-indent: -9999px;
}
a:hover.switch_thumb {
        filter:alpha(opacity=75);
        opacity:.75;
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)";
}
a.swap { background-position: left bottom; }


</style>

Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript" src="/javascript/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 
        $("a.switch_thumb").toggle(function(){
          $(this).addClass("swap");
          $("ul.display").fadeOut("fast", function() {
                  $(this).fadeIn("fast").addClass("thumb_view");
                });
          }, function () {
      $(this).removeClass("swap");
          $("ul.display").fadeOut("fast", function() {
                  $(this).fadeIn("fast").removeClass("thumb_view");
                });
        });

});
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<a href="javascript:void(0);" class="switch_thumb">Switch Thumb</a>
<ul style="display: block;" class="display">
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample2.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample3.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample4.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample5.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample6.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample7.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample8.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample9.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. Woman kickin', work yer last dogs, rattler hee-haw
mobilehome stew trailer driveway shootin'.</p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample10.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample11.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin', jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors spell. </p>
                </div>
        </li>
        <li>
                <div class="content_block">
                        <a href="#"><img src="sample12.gif" alt=""></a>
                        <h2><a href="#">Image Name</a></h2>
                        <p>Askin',
jehosephat come pudneer, sam-hell, in lament had. Cabin tax-collectors
spell, chitlins spittin' watchin' hootch me rightly kinfolk that. Woman
kickin', work yer last dogs, rattler hee-haw mobilehome stew trailer
driveway shootin'. </p>
                </div>
        </li>
</ul>

Step 4: downloads
Files
Picture_Gallery_with_Display_Switcher_images.zip







JavaScriptBank 02-15-2011 07:59 PM

JavaScript Proper Social Security Number Validation
 
One more JavaScript code example to accept numeric characters. But this JavaScript will work in the different manner, it on... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Mr. J | http://www.huntingground.net
// This script downloaded from www.JavaScriptBank.com

function advance2(currentField,nextField,limit) {
  if(nextField!="rset"&&document.myForm2[currentField].value.length == limit){
    document.myForm2[nextField].select();
  } else {
    if (document.myForm2[currentField].value.length == limit) {
      document.myForm2[currentField].maxLength=limit
      document.myForm2[nextField].select()
      document.myForm2[nextField].disabled=false
      document.myForm2[currentField].blur()
      document.myForm2[nextField].style.backgroundColor="#EFCCA4"
    }
  }
}
</script>

Step 2: Place HTML below in your BODY section
HTML
Code:

<p>
This form is formatted for a social security number (XXX-XX-XXXX).</p>

<form name="myForm2" onreset="this.rset.disabled='true'; this.rset.style.backgroundColor=''">
<input type="text" name="t1" size="6" onclick="select()" onKeyUp="advance2('t1','t2',3)">
<input type="text" name="t2" size="6" onclick="select()" onKeyUp="advance2('t2','t3',2)">
<input type="text" name="t3" size="6" onclick="select()" onKeyUp="advance2('t3','rset',4)">
<input type="reset" name="rset" onclick="this.blur()" disabled>
</form>

<div style="text-align: left; width: 70%;">
<p>
The limit for each individual field is passed to the function by the appropriate input event, as shown in the form using the format: <code>onKeyUp="advance2('currentField','nextField',limit)</code>"</p>
</div>







JavaScriptBank 02-15-2011 09:10 PM

JavaScript Add-Remove HTML Elements with DOM
 
This JavaScript code example will dynamically add/remove HTML elements with content included within them according to ... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Dustin Diaz | http://www.dustindiaz.com/
// This script downloaded from www.JavaScriptBank.com

var Dom = {
  get: function(el) {
    if (typeof el === 'string') {
      return document.getElementById(el);
    } else {
      return el;
    }
  },
  add: function(el, dest) {
    var el = this.get(el);
    var dest = this.get(dest);
    dest.appendChild(el);
  },
  remove: function(el) {
    var el = this.get(el);
    el.parentNode.removeChild(el);
  }
};
var Event = {
  add: function() {
    if (window.addEventListener) {
      return function(el, type, fn) {
        Dom.get(el).addEventListener(type, fn, false);
      };
    } else if (window.attachEvent) {
      return function(el, type, fn) {
        var f = function() {
          fn.call(Dom.get(el), window.event);
        };
        Dom.get(el).attachEvent('on' + type, f);
      };
    }
  }()
};
Event.add(window, 'load', function() {
  var i = 0;
  Event.add('add-element', 'click', function() {
    var el = document.createElement('p');
    el.innerHTML = 'Remove This Element (' + ++i + ')';
    Dom.add(el, 'content');
    Event.add(el, 'click', function(e) {
      Dom.remove(this);
    });
  });
});
</script>

Step 2: Place HTML below in your BODY section
HTML
Code:

<div id="doc">

  <p id="add-element">Add Elements</p>
  <div id="content"></div>
</div>







JavaScriptBank 02-15-2011 09:39 PM

JavaScript Filename Array Maker
 
During coding JavaScript applications, we usually have to work with many JavaScript arrays; and sometimes declare/initiate them is the time-consuming tasks.

For this reason, I would like to present... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use CSS code below for styling the script
CSS
Code:

<style type="text/css">
#display {
  position: relative;
  left: 10px;
  width: 450px;
  border: 1px solid black;
  padding: 10px;
}
</style>

Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Mr. J | http://www.huntingground.net/
// This script downloaded from www.JavaScriptBank.com

function init(){
  array_name=document.f1.t1.value //name of array
  val2=document.f1.t3a.value
  ext=document.f1.t4.value
  for(r=0;r<document.f1.r1.length;r++){ // check which r1 radio is selected
    if(document.f1.r1[r].checked==true){
      option=document.f1.r1[r].value // selected radio value
    }
  }

  if(option==0){
    document.getElementById("display").innerHTML=array_name+" = new Array(" // opening array type 1
  } else {
    document.getElementById("display").innerHTML=array_name+" = new Array()<br>" // opening array type 2 & 3
  }

  if(document.f1.r2[0].checked==true){ // if indexed values
    make_array1()
  }

  if(document.f1.r2[1].checked==true){ // if non index values
    make_array2()
  }
}

function make_array1(){
  array_length=document.f1.t2.value-1 // length of array
  index_values=document.f1.t3.value // index value

  if(array_length==""||array_length==0){ // make sure a viable number is used
    document.getElementById("display").innerHTML="Please Enter a Number"
    document.f1.b2.disabled=true
    return
  } else {
    if(!ns){document.f1.cpy.disabled=false}
  }

  for(num=0;num<array_length;num++){
    j=num
    if(num<10){num="00"+num}
    if(num>9&&num<100){num="0"+num}
    if(document.f1.t4.value.length>0){
      i=num+val2+ext}
      else{i=num+val2}

  if(option==0){ // insert inner indexes for type 1
    document.getElementById("display").innerHTML+="\""+index_values+i+"\", "
  } else {
    if(option==1){ // insert inner indexes for type 2
      document.getElementById("display").innerHTML+=array_name+"["+j+"]="
      document.getElementById("display").innerHTML+="\""+index_values+i+"\"<br>"
    } else { // insert inner indexes for type 3
      document.getElementById("display").innerHTML+=array_name+"["+array_name+".length]=\""+index_values+i+"\"<br>"
    }
  }
}

if(num<10){num="00"+num}
if(num>9&&num<100){num="0"+num}
if(num>100){num=num}

if(document.f1.t4.value.length>0){
  i= num+val2+ext}
  else{i=num+val2}

  if(option==0){ // insert last indexes for type 1
    document.getElementById("display").innerHTML+="\""+index_values+i+"\")"
  } else {
    if(option==1){ // insert last indexes for type 2
      document.getElementById("display").innerHTML+=array_name+"["+(j+1)+"]="
      document.getElementById("display").innerHTML+="\""+index_values+i+"\"<br>"
    } else { // insert last indexes for type 3
      document.getElementById("display").innerHTML+=array_name+"["+array_name+".length]=\""+index_values+i+"\"<br>"
    }
  }
}

index_value=new Array()
count= 0
last=0

function make_array2(){
  if(!ns){document.f1.cpy.disabled=false}
  for(r=0;r<document.f1.r1.length;r++){ // check which r1 radio is selected
    if(document.f1.r1[r].checked==true){
      chkrad=r
    }
  }
  if(chkrad!=last){ // prevent additional index when only changing array style
    count--
  }

  if(document.f1.t4.value.length>0){
    index_value[count]=document.f1.t3.value+ext}
  else {
    index_value[count]=document.f1.t3.value
  }

  for(i=0;i<count;i++){
    if(option==0){
      document.getElementById("display").innerHTML+="\""+index_value[i]+"\", "
    } else {
      if(option==2){
        document.getElementById("display").innerHTML+=array_name+"["+array_name+".length]=\""+index_value[i]+"\"<br>"
      } else {
        document.getElementById("display").innerHTML+=array_name+"["+i+"]=\""+index_value[i]+"\"<br>"
      }
    }
  }

  if(option==0){
    document.getElementById("display").innerHTML+="\""+index_value[i]+"\")"
  } else {
    if(option==2){
      document.getElementById("display").innerHTML+=array_name+"["+array_name+".length]=\""+index_value[i]+"\"<br>"
    } else {
      document.getElementById("display").innerHTML+=array_name+"["+i+"]=\""+index_value[i]+"\"<br>"
    }
  }
  count++
  document.f1.t3.select()
  last=chkrad
}

function oreset(){
  count=0
  document.f1.t3.value=""
  document.getElementById("display").innerHTML=""
  document.f1.t3.select()
}

function chk(){
  if(document.f1.r2[0].checked==true){
    document.f1.t2.disabled=false
    document.getElementById("sp").disabled=false
    document.f1.t2.style.backgroundColor="#FFFFFF"
    document.f1.b1.disabled=false
    document.f1.b2.disabled=true
    document.f1.b3.disabled=true
    document.f1.t3a.disabled=false
    document.f1.t3a.style.backgroundColor="#FFFFFF"
  } else {
    document.f1.t2.disabled=true
    document.getElementById("sp").disabled=true
    document.f1.t2.style.backgroundColor="#c0c0c0"
    document.f1.b1.disabled=true
    document.f1.b2.disabled=false
    document.f1.b3.disabled=false
    document.f1.t3.select()
    document.f1.t3a.disabled=true
    document.f1.t3a.style.backgroundColor="#c0c0c0"
  }
}

function Copy(id){
  if(ns){
    alert("Sorry, Netscape does not recongise this function")
    document.f1.cpy.disabled=true
    return
  }
  copyit=id
  textRange = document.body.createTextRange();
  textRange.moveToElementText(copyit);
  textRange.execCommand("Copy");
  alert("Copying Complete.\n\nPlease Paste into your SCRIPT")
}

ns=document.getElementById&&!document.all

function getKey(e) {
  pressed_key=(!ns)?event.keyCode:e.which
  if( pressed_key==13){
    init()
  }
}
document.onkeypress = getKey;
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<form name="f1">

<table border="0">
  <tr>
    <td>Array Name:</td>
    <td colspan="6">
      <input type="text" name="t1" value="myArray">
    </td>
  </tr><tr>
    <td>

      <span id="sp">Indexed Array Length:</span>
    </td>
    <td colspan="6">
      <input type="text" name="t2" value="5" size="3" maxlength="3">
    </td>
  </tr><tr>
    <td>Index Value:</td>
    <td colspan="6">

      <input type="text" name="t3" value="image" size="10">
      <input type="text" name="t3a" value="_tn" size="10"> Ext
      <input type="text" name="t4" value=".jpg" size="4" maxlength="4">
    </td>
  </tr><tr>
    <td>Index Style:</td>
    <td align="right">1
      <input type="radio" name="r1" value="0" checked onclick="init()">
    </td>

    <td> </td>
    <td align="right">2
      <input type="radio" name="r1" value="1" onclick="init()">
    </td>
    <td> </td>
    <td align="right">3
      <input type="radio" name="r1" value="2" onclick="init()">
    </td>
    <td width="80"> </td>

  </tr><tr>
    <td>Add Numerical Values:</td>
    <td align="right">Yes
      <input type="radio" name="r2" value="0" checked onclick="chk()">
    </td>
    <td align="center"> </td>
    <td align="right">No
      <input type="radio" name="r2" value="1" onclick="chk()">
    </td>

    <td> </td>
    <td colspan="2"> </td>
  </tr><tr align="center">
    <td>
      <input type="button" name="b1" value="Numerical Enter" onclick="init()">
    </td>
    <td colspan="6">
      <input type="button" name="cpy" value="Copy Array" onclick="Copy(display)" disabled>

      <input type="button" name="b2" value="Manual Enter" onclick="init()" disabled>
      <input type="button" name="b3" value="Restart" onclick="oreset()" disabled>
    </td>
  </tr>
</table>

</form>

<div id="display"></div>







movie 02-21-2011 07:31 PM

very interesting solution you have found

JavaScriptBank 02-23-2011 09:01 PM

jQuery JavaScript Countdown Timer with Bar Display
 
This is really a cool JavaScript code example to display an amazing JavaScript countdown timer on your web pages. With the support of the powerful JavaScript framework - jQuery - you can set the point... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use CSS code below for styling the script
CSS
Code:

<style type="text/css" media="screen">
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
  #seconds-box,#minutes-box,#hours-box,#days-box {
  width: 222px;
  height: 30px;
  background: #eee;
  border: 1px solid #ccc;
        }

  #seconds-outer,#minutes-outer,#hours-outer,#days-outer {
  margin: 10px;
  width: 200px;
  height: 9px;
  border: 1px solid #aaa;
  background: #f3f3f3;
  }
 
  #seconds-inner,#minutes-inner,#hours-inner,#days-inner {
  height: 100%;
  width: 100%;
  background: #c00;
  }

        #seconds-count,#minutes-count,#hours-count,#days-count {
            float: left;
            font-size: 0.9em;
            margin-left: -200px;
            margin-top: 7px;
         
        }

 </style>

Step 2: Copy & Paste JavaScript code below in your HEAD section
JavaScript
Code:

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

/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
    function timeleft(timetype){
        days=0;hours=0;mins=0;
        var e = new Date(2010,11,25,0,0,0);
        var now  = new Date();
        var left = e.getTime() - now.getTime();

        left = Math.floor(left/1000);
  days = Math.floor(left/86400);
  left = left%86400;
  hours=Math.floor(left/3600);
  left=left%3600;
  mins=Math.floor(left/60);
  left=left%60;
  secs=Math.floor(left);

        switch(timetype){
            case "s":
                return secs;
                break;
            case "m":
                return mins;
                break;
            case "h":
                return hours;
                break;
            case "d":
                return days;
                break;
        }
    }

    function set_start_count(){
        set_hour_count();
        set_minute_count();
        set_day_count();
    }

    function set_day_count(){
        d=timeleft('d');
        $('#days-count').text(d.toString() + ' day(s)');
    }

    function set_hour_count(){
        h=timeleft('h');
        $('#hours-count').text(h.toString() + ' hour(s)');
    }

    function set_minute_count(){
        m = timeleft('m');
        $('#minutes-count').text(m.toString()+ ' minute(s)');
    }
    function set_second_count(){
        s = timeleft('s');
        $('#seconds-count').text(s.toString() + ' second(s)');
    }

    function update_minute(){
        var now = new Date();
        var mw = $('#minutes-outer').css('width');
        mw = mw.slice(0,-2);
        var s = now.getSeconds();
        sleft = (60 - s)
        if (sleft == 0)
        {
            sleft=60;
        }
        m = ((sleft/60)*mw).toFixed();
        $('#minutes-inner').css({width:m});
        return sleft*1000;
    }

    function update_hour(){
        var now = new Date();
        var mw = $('#hours-outer').css('width');
        mw = mw.slice(0,-2);
        var s = now.getMinutes();
        sleft = 60 - s
        m = ((sleft/60)*mw).toFixed();

        $('#hours-inner').css({width: m});
        return sleft*(1000*60);
    }

    function update_day(){

        var now = new Date();
        var mw = $('#days-outer').css('width');
        mw = mw.slice(0,-2);
        var s = now.getHours();
        sleft = 24 - s
        m = ((sleft/24)*mw).toFixed();

        $('#days-inner').css({width: m });
        return sleft*(1000*60*24);
    }

    function reset_day(){
        $('#days-inner').width($('#days-outer').width());
        start_countdown_day();
    }

    function reset_hour(){
        $('#hours-inner').width($('#hours-outer').width());
        start_countdown_hour();
    }

    function reset_second(){
        $('#seconds-inner').width($('#seconds-outer').width());
        start_countdown_second();
    }

    function reset_minute(){
        $('#minutes-inner').width($('#minutes-outer').width());
        start_countdown_minute();
    }

    function start_countdown_second(){
        set_second_count();
        now = new Date();
        $('#seconds-inner').animate({width: 0}, 1000,reset_second);
    }

    function start_countdown_minute(){
        set_minute_count();
        $('#minutes-inner').animate({width: 0}, update_minute(),reset_minute);
        //update_minute());
    }

    function start_countdown_hour(){
        set_hour_count();
        $('#hours-inner').animate({width: 0},update_hour(),reset_hour);
    }

    function start_countdown_day(){
        set_day_count();
        $('#days-inner').animate({width: 0},update_day(),reset_day);
    }

    $(document).ready( function(){
        start_countdown_second();
        start_countdown_minute();
        start_countdown_hour();
        start_countdown_day();
    });
</script>

Step 3: Place HTML below in your BODY section
HTML
Code:

<center>
 
 <div id="days-box">
    <div id="days-count"> </div>
    <div id="days-outer">
        <div id="days-inner"> </div>
    </div>
 </div>


 <div id="hours-box">
    <div id="hours-count"> </div>
    <div id="hours-outer">
        <div id="hours-inner"> </div>
    </div>
 </div>

 <div id="minutes-box">
    <div id="minutes-count"> </div>
    <div id="minutes-outer">
        <div id="minutes-inner"> </div>
    </div>
 </div>

<div id="seconds-box">
    <div id="seconds-count"> </div>
    <div id="seconds-outer">
        <div id="seconds-inner"> </div>
    </div>
 </div>

</center>

Step 4: downloads
Files
jquery.js







JavaScriptBank 02-23-2011 09:33 PM

JavaScript Dynamic Drop Down Values on Action
 
If your web pages have a huge list of options to show in the drop down menus (listed into categories), why don't you consider to use this JavaScri... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Place JavaScript below in your HEAD section
JavaScript
Code:

<script type="text/javascript">
// Created by: Sandeep Gangadharan | http://www.sivamdesign.com/scripts/
// This script downloaded from www.JavaScriptBank.com

function changer(link) {
  if (link=="") {
    return; }

//======================
// Edit this portion below. For each new state copy and paste
// the entire IF statement and change the name of the state and the cities.
// Make sure the spelling of the state is the same in the IF statement and in the link.

  if (link=="Arizona") {
    document.theForm.theState.value="Arizona";
    var theOptions=new Array (
      "Bisbee",
      "Deer Valley",
      "Flagstaff",
      "Mesa",
      "Phoenix"); }
  else if (link=="California") {
    document.theForm.theState.value="California";
    var theOptions=new Array (
      "Alameda",
      "Bakersfield",
      "Burbank",
      "Los Angeles"); }
  else if (link=="Florida") {
    document.theForm.theState.value="Florida";
    var theOptions=new Array (
      "Altamonte Springs",
      "Boca Raton",
      "Miami",
      "West Palm Beach"); }
  else if (link=="New York") {
    document.theForm.theState.value="New York";
    var theOptions=new Array (
      "Albany",
      "East Rockaway",
      "New York City"); }

// Do not edit anything below this line:
//======================

  i = document.theForm.secondChoice.options.length;
    if (i > 0) {
      document.theForm.secondChoice.options.length -= i; document.theForm.secondChoice.options[i] = null;
    }

  var theCount=0;
  for (e=0; e<theOptions.length; e++) {
    document.theForm.secondChoice.options[theCount] = new Option();
    document.theForm.secondChoice.options[theCount].text = theOptions[e];
    document.theForm.secondChoice.options[theCount].value = theOptions[e];
    theCount=theCount+1; }
}

//  NOTE: [document.theForm.theState.value] will get you the name of the state,
//  and [document.theForm.secondChoice.value] the name of the city chosen
</script>

Step 2: Place HTML below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<form name=theForm>
  <strong>Select a State:</strong><br>

  <a href="javascript:changer('Arizona')">Arizona</a> |
  <a href="javascript:changer('California')">California</a> |
  <a href="javascript:changer('Florida')">Florida</a> |
  <a href="javascript:changer('New York')">New York</a>
  <br><br>
  <strong>Then ...</strong><br>

  <input type="hidden" name="theState">
  <select name="secondChoice">
    <option value="">Select a City</option>
  </select>
</form>







JavaScriptBank 02-23-2011 10:20 PM

Build Simple Flash Timer Countdown in ActionScript
 
Countdown timer for an event seems to be an indispensable thing in the modern life of human, we can see them in the holidays of Christmas, new year, birthday, etc. Or easily, we can see them daily in ... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup







JavaScriptBank 02-23-2011 10:59 PM

Simple JavaScript for Auto-Sum with Checkboxes
 
This JavaScript code example uses a for loop to calculate the sum of JavaScript checkbox values. This JavaScript will display a running total automatically wh... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Copy & Paste JavaScript code below in your HEAD section
JavaScript
Code:

<script type="text/javascript">
// Created by: Jay Rumsey | http://www.nova.edu/~rumsey/
// This script downloaded from JavaScriptBank.com

function UpdateCost() {
  var sum = 0;
  var gn, elem;
  for (i=0; i<5; i++) {
    gn = 'game'+i;
    elem = document.getElementById(gn);
    if (elem.checked == true) { sum += Number(elem.value); }
  }
  document.getElementById('totalcost').value = sum.toFixed(2);
}
</script>

Step 2: Place HTML below in your BODY section
HTML
Code:

<input type="checkbox" id='game0' value="9.99"  onclick="UpdateCost()">Game 1 ( 9.99)<br>
<input type="checkbox" id='game1' value="19.99" onclick="UpdateCost()">Game 2 (19.99)<br>
<input type="checkbox" id='game2' value="27.50" onclick="UpdateCost()">Game 3 (27.50)<br>
<input type="checkbox" id='game3' value="45.65" onclick="UpdateCost()">Game 4 (45.65)<br>
<input type="checkbox" id='game4' value="87.20" onclick="UpdateCost()">Game 5 (87.20)<br>







JavaScriptBank 03-10-2011 08:42 PM

Simple Auto Image Rotator with jQuery
 
This is a simple JavaScript code example to rotate your pictures continuously. This jQuery code example uses the blur effects for the animations of picture transitions. A very easy JavaScript code exa... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Place CSS below in your HEAD section
CSS
Code:

<style type="text/css">
/* rotator in-page placement */
    div#rotator {
        position:relative;
        height:345px;
        margin-left: 15px;
}
/* rotator css */
        div#rotator ul li {
        float:left;
        position:absolute;
        list-style: none;
}
/* rotator image style */       
        div#rotator ul li img {
        border:1px solid #ccc;
        padding: 4px;
        background: #FFF;
}
    div#rotator ul li.show {
        z-index:500
}
</style>

Step 2: Copy & Paste JavaScript code below in your HEAD section
JavaScript
Code:

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

<!-- By Dylan Wagstaff, http://www.alohatechsupport.net -->
<script type="text/javascript">

function theRotator() {
        //Set the opacity of all images to 0
        $('div#rotator ul li').css({opacity: 0.0});
       
        //Get the first image and display it (gets set to full opacity)
        $('div#rotator ul li:first').css({opacity: 1.0});
               
        //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds
        setInterval('rotate()',6000);
       
}

function rotate() {       
        //Get the first image
        var current = ($('div#rotator ul li.show')?  $('div#rotator ul li.show') : $('div#rotator ul li:first'));

        //Get next image, when it reaches the end, rotate it back to the first image
        var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));       
       
        //Set the fade in effect for the next image, the show class has higher z-index
        next.css({opacity: 0.0})
        .addClass('show')
        .animate({opacity: 1.0}, 1000);

        //Hide the current image
        current.animate({opacity: 0.0}, 1000)
        .removeClass('show');
       
};

$(document).ready(function() {               
        //Load the slideshow
        theRotator();
});

</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<div id="rotator">
  <ul>
    <li class="show"><a href="http://www.alohatechsupport.net/webdesignmaui/"><img src="image-1.jpg" width="500" height="313"  alt="pic1" /></a></li>
    <li><a href="http://www.alohatechsupport.net/"><img src="image-2.jpg" width="500" height="313"  alt="pic2" /></a></li>
    <li><a href="http://www.alohatechsupport.net/mauiwebdesign.html"><img src="image-3.jpg" width="500" height="313"  alt="pic3" /></a></li>

    <li><a href="http://www.alohatechsupport.net/webdesignmaui/maui-web-site-design/easy_jquery_auto_image_rotator.html"><img src="image-4.jpg" width="500" height="313"  alt="pic4" /></a></li>
  </ul>
</div>

Step 4: must download files below
Files
jquery.js
image-1.jpg
image-2.jpg
image-3.jpg
image-4.jpg







JavaScriptBank 03-10-2011 09:19 PM

Awesome Canvas Drawer with HTML5
 
Although HTML5 is still developed but at present we still can enjoy many amazing web applications for HTML5, they're also presented on jsB@nk:

- detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: must download files below
Files
Awesome Canvas Drawer with HTML5.zip







JavaScriptBank 03-10-2011 09:59 PM

JavaScript RegEx Example Code for Text Input Limitations
 
One more JavaScript code example to limit user inputs with many options: non-alphanumeric characters with spaces, removes ex... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Ilya Gerasimenko | http://www.gerasimenko.com/
// This script downloaded from www.JavaScriptBank.com

// clean lines
cleanUpLine = function (str,limit) { // clean string
        var clean_pass1 = str.replace(/\W/g, ' ');        //replace punctuation with spaces
        var clean_pass2 = clean_pass1.replace(/\s{2,}/g, ' ');                // compact multiple whitespaces
        var clean_pass3 = clean_pass2.replace(/^\s+|\s+$/g, '');        // trim whitespaces from beginning or end of string
        var clean_pass4 = clean_pass3.substring(0,limit);                        // trim string
        return clean_pass4;
}

// number of keywords and keyword length validation
cleanUpList = function (fld) {
        var charLimit = 20;                // ADJUST: number of characters per line
        var lineLimit = 10;                // ADJUST: number of lines
        var cleanList = [];
        var re1 = /\S/;                        // all non-space characters
  var re2 = /[\n\r]/;                // all line breaks
        var tempList = fld.value.split('\n');
        for (var i=0; i<tempList.length;i++) {
                  if (re1.test(tempList[i])) { // store filtered lines in an array
                          var cleanS = cleanUpLine(tempList[i],charLimit);
                          cleanList.push(cleanS);
                  }
  }
  for (var j=0; j<tempList.length;j++) {
                  if (tempList[j].length > charLimit && !re2.test(tempList[j].charAt(charLimit))) { // make sure that last char is not a line break - for IE compatibility
                  fld.value = cleanList.join('\n'); // restore from array
                  }
        }
        if (cleanList.length > lineLimit) {
                  cleanList.pop();        // remove last line
                  fld.value = cleanList.join('\n'); // restore from array
        }
        fld.onblur = function () {this.value = cleanList.join('\n');} // onblur - restore from array
}       

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(
  function () {
                  document.form.word_list.onkeyup =        function () {
                                  cleanUpList(document.form.word_list);
                  }
  }
);
</script>

Step 2: Place HTML below in your BODY section
HTML
Code:

Textarea below has limitations: 20 characters and 10 lines<br />
<form name="form">

        <textarea cols="22" rows="12" name="word_list" id="word_list"></textarea>
</form>







JavaScriptBank 03-22-2011 11:06 PM

Cool JavaScript Date Picker
 
A very simple JavaScript code example to create the amazing date pickers. This JavaScript date picker script will display pickers with the layout of calendar to allow users pick the date.

Within a ... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: must download files below
Files
Cool JavaScript Date Picker.zip







JavaScriptBank 03-23-2011 01:41 AM

Random of Testimonial Bubbles with XML and jQuery
 
This JavaScript code example uses jQuery framework and a XML file to create a section for displaying random of testimonial bubbles. It has an amazing design for layout and the testimonials will be dis... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: must download files below
Files
Random of Testimonial Bubbles with XML and jQuery.zip







JavaScriptBank 03-23-2011 02:13 AM

Simple Awesome Inline Modal Box with CSS3
 
Like JavaScript popup scripts ever presented on jsB@nk:

- [URL="http://www.javascriptbank.com/greybox-cool-html-javascript-ajax-flash-window-popup.html"]GreyBox: Cool HTML/JavaScript/AJAX/Flash... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use CSS code below for styling the script
CSS
Code:

<style type="text/css">
#popup{       
z-index+999999;
position:absolute;
left:400px;
top:200px;
padding:10px;
display:none;
width:400px;
height:200px;
background: #FFFFFF;
box-shadow: 5px 5px 5px #ccc;
-moz-box-shadow: 5px 5px 5px #ccc;
-webkit-box-shadow: 5px 5px 5px #ccc;
}
.tit{
width:98%;
height:20px;
padding:5px;
background:#3654A8;
}
</style>

Step 2: Place JavaScript below in your HEAD section
JavaScript
Code:

<script type="text/javascript" language="JavaScript">
function ShowHide(divId)
{
        if(document.getElementById(divId).style.display == 'none')
        {
        document.getElementById(divId).style.display='block';
        document.bgColor="silver" ;
        }
        else
        {
        document.getElementById(divId).style.display = 'none';
        document.bgColor="#FFFFFF" ;
        }
}
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<div class="body">
               
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque dignissim volutpat sem ac scelerisque. Cras non rutrum lorem. Duis lacinia quam at leo ultrices commodo. Ut eget urna feugiat odio lobortis condimentum. Donec ultrices eros id mi bibendum feugiat. Vestibulum augue eros, ultrices id viverra at, euismod sed neque. Pellentesque non magna vitae velit venenatis condimentum. Phasellus eleifend tristique odio eget posuere. Nulla lacinia molestie quam at luctus. Vestibulum non lorem velit.</p>
                               
        <p>Nulla venenatis pretium urna. Suspendisse nisl orci, congue a gravida a, ornare id ipsum. Duis sapien nulla, congue id dictum eget, sollicitudin non nisi. Integer congue dictum augue ac fermentum. Etiam nec semper dui. Pellentesque rutrum lobortis neque in imperdiet. Donec ut lacus felis, id scelerisque nisi. Maecenas lacus erat, cursus nec facilisis non, aliquet ut felis. Aenean <a href="javascript:void(0);" onclick="return ShowHide('popup');"><b>Click Here for PopUp</b></a>. Nam sit amet magna in quam cursus porttitor. Maecenas laoreet blandit tellus, at volutpat turpis suscipit et. Maecenas tempus convallis magna. Vivamus venenatis dolor quis ligula laoreet tristique. Praesent euismod porttitor ligula, vitae iaculis quam faucibus non. Sed sagittis ullamcorper erat vel porttitor.</p>
                               
        <p>Suspendisse convallis vehicula ligula, in pellentesque lacus dictum in. Nam a ante eros, vitae luctus mauris. Sed tempus tellus at purus semper ac viverra nulla hendrerit. Quisque condimentum vestibulum cursus. Pellentesque vehicula commodo nisl, quis blandit tortor consequat sed. Praesent sed orci nisl. Donec id justo eu elit elementum convallis ac at metus. Nam quis erat ut lorem facilisis eleifend. Phasellus et velit sed nulla sodales blandit quis sed massa. Praesent suscipit auctor luctus. Praesent eleifend, est sit amet vestibulum placerat, mi erat placerat arcu, non luctus enim tellus a felis. Sed sed sapien dolor. Nulla vestibulum mattis ante, in convallis mauris tempor nec. Proin aliquam arcu eu orci luctus adipiscing. Etiam pulvinar, justo sed volutpat mattis, erat purus gravida sem, vitae pretium eros velit sit amet dolor. </p>
       
        </div>
        <div id="popup">

                <div class="tit">Your Title </div>
                <p>Suspendisse convallis vehicula ligula, in pellentesque lacus dictum in. Nam a ante eros, vitae luctus mauris. Sed tempus tellus at purus semper ac viverra nulla </p>
                <a href="javascript:void(0);" onclick="return ShowHide('popup');">Close</a>
        </div>







JavaScriptBank 03-30-2011 07:31 PM

JavaScript Loading Progress Effect with jQuery
 
A very unique and amazing JavaScript code example to create JavaScript loading progress effects on the web pages. With this ver... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: must download files below
Files
JavaScript Loading Progress Effect with jQuery.zip







JavaScriptBank 03-30-2011 08:04 PM

Simple JavaScript Code for Layer Display Toggle
 
One more JavaScript code example to show/hide a layer every time the users click the specified text link. In live demo of this JavaScript code example, the script used to toggle the comments in a post... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: CSS below for styling thescript, place it into HEAD section
CSS
Code:

<style type="text/css">
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/

div.quote
{
        margin-left: 25%;
        padding: 10px;
        background-color: #FFCF31;
        border: 1px solid #00009C;
        width: 450px;
        text-align: left;
}

div.quote p {
        font-size: .8em;
        margin: 0px 0px 0px 0px;
}

div#commentForm {
        display: none;
        margin: 0px 20px 0px 20px;
        font-family: Arial, sans-serif;
        font-size: .8em;
}

a.commentLink {
        font-family: Arial, sans-serif;
        font-size: .9em;
}
</style>

Step 2: Place JavaScript below in your HEAD section
JavaScript
Code:

<script type="text/javascript">
// Created by: Justin Barlow | http://www.netlobo.com
// This script downloaded from www.JavaScriptBank.com

function toggleLayer(whichLayer) {
  var elem, vis;
  if(document.getElementById) // this is the way the standards work
    elem = document.getElementById(whichLayer);
  else if(document.all) // this is the way old msie versions work
      elem = document.all[whichLayer];
  else if(document.layers) // this is the way nn4 works
    elem = document.layers[whichLayer];
  vis = elem.style;
  // if the style.display value is blank we try to figure it out here
  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<div class="quote">

<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent porttitor luctus quam. Pellentesque diam libero, feugiat quis, porttitor sagittis, suscipit dignissim, pede. Duis dapibus mauris at enim. Morbi vehicula turpis nec massa.</p>
<p style="text-align: right;"><a class="commentLink" title="Add a comment to this entry" href="javascript:toggleLayer('commentForm');">Add a comment</a>

<div id="commentForm">
<form id="addComment" action="" method="get">
        <p>Name:<br>
        <input name="name"><br>
        Comment:<br>
        <textarea rows="3" cols="40" name="comment"></textarea><br>

        <input name="submit" value="Add Comment" type="submit"> <input onclick="javascript:toggleLayer('commentForm');" name="reset" value="Cancel" type="reset"></p>
</form>
</div>

</div>







JavaScriptBank 03-30-2011 08:46 PM

Cool JavaScript Digital Countdown with jQuery
 
A very amazing JavaScript countdown timer script with cool layout to display on your web pages. This JavaScript timer countd... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Download files below
Files
Cool JavaScript Digital Countdown with jQuery.zip







JavaScriptBank 04-24-2011 09:25 PM

Auto Thousand-Grouped Number Input Fields
 
One more JavaScript code example to build an auto thousand-grouped number after the users finish to type. JavaScript source code looks good and very easy to use.... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Place JavaScript below in your HEAD section
JavaScript
Code:

<script type="text/javascript">

// Created by: Pavel Donchev | http://chameleonbulgaria.com/
// This script downloaded from www.JavaScriptBank.com

function currency(which){
                currencyValue = which.value;
                currencyValue = currencyValue.replace(",", "");
                decimalPos = currencyValue.lastIndexOf(".");
                if (decimalPos != -1){
                                decimalPos = decimalPos + 1;
                }
                if (decimalPos != -1){
                                decimal = currencyValue.substring(decimalPos, currencyValue.length);
                                if (decimal.length > 2){
                                                decimal = decimal.substring(0, 2);
                                }
                                if (decimal.length < 2){
                                                while(decimal.length < 2){
                                                        decimal += "0";
                                                }
                                }
                }
                if (decimalPos != -1){
                                fullPart = currencyValue.substring(0, decimalPos - 1);
                } else {
                                fullPart = currencyValue;
                                decimal = "00";
                }
                newStr = "";
                for(i=0; i < fullPart.length; i++){
                                newStr = fullPart.substring(fullPart.length-i-1, fullPart.length - i) + newStr;
                                if (((i+1) % 3 == 0) & ((i+1) > 0)){
                                                if ((i+1) < fullPart.length){
                                                        newStr = "," + newStr;
                                                }
                                }
                }
                which.value = newStr + "." + decimal;
}

function normalize(which){
                alert("Normal");
                val = which.value;
                val = val.replace(",", "");
                which.value = val;
}

</script>

Step 2: Copy & Paste HTML code below in your BODY section
HTML
Code:

$ <input type="text" name="currencyField1" onchange="currency(this);" />






JavaScriptBank 04-24-2011 09:57 PM

Awesome Tabbing Navigation with Prototype and AJAX
 
A very cool JavaScript code example to create tabbing navigation menus for display information on your web pages. This tabb... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Download files below
Files
Awesome Tabbing Navigation with Prototype and AJAX.zip







JavaScriptBank 04-25-2011 01:58 AM

XMLWriter: Simple JavaScript XML Creator
 
XML - a type of data defining - becoming more popular at present because of its flexibility and convenience, data defined by XML become more visual and... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Ariel Flesler | http://flesler.blogspot.com/2008/03/xmlwriter-for-javascript.html
// Licensed under: BSD License
// This script downloaded from www.JavaScriptBank.com

/**
 * XMLWriter - XML generator for Javascript, based on .NET's XMLTextWriter.
 * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
 * Date: 3/12/2008
 * @version 1.0.0
 * @author Ariel Flesler
 * http://flesler.blogspot.com/2008/03/xmlwriter-for-javascript.html
 */
 
function XMLWriter( encoding, version ){
        if( encoding )
                this.encoding = encoding;
        if( version )
                this.version = version;
};
(function(){
       
XMLWriter.prototype = {
        encoding:'ISO-8859-1',// what is the encoding
        version:'1.0', //what xml version to use
        formatting: 'indented', //how to format the output (indented/none)  ?
        indentChar:'\t', //char to use for indent
        indentation: 1, //how many indentChar to add per level
        newLine: '\n', //character to separate nodes when formatting
        //start a new document, cleanup if we are reusing
        writeStartDocument:function( standalone ){
                this.close();//cleanup
                this.stack = [ ];
                this.standalone = standalone;
        },
        //get back to the root
        writeEndDocument:function(){
                this.active = this.root;
                this.stack = [ ];
        },
        //set the text of the doctype
        writeDocType:function( dt ){
                this.doctype = dt;
        },
        //start a new node with this name, and an optional namespace
        writeStartElement:function( name, ns ){
                if( ns )//namespace
                        name = ns + ':' + name;
               
                var node = { n:name, a:{ }, c: [ ] };//(n)ame, (a)ttributes, (c)hildren
               
                if( this.active ){
                        this.active.c.push(node);
                        this.stack.push(this.active);
                }else
                        this.root = node;
                this.active = node;
        },
        //go up one node, if we are in the root, ignore it
        writeEndElement:function(){
                this.active = this.stack.pop() || this.root;
        },
        //add an attribute to the active node
        writeAttributeString:function( name, value ){
                if( this.active )
                        this.active.a[name] = value;
        },
        //add a text node to the active node
        writeString:function( text ){
                if( this.active )
                        this.active.c.push(text);
        },
        //shortcut, open an element, write the text and close
        writeElementString:function( name, text, ns ){
                this.writeStartElement( name, ns );
                this.writeString( text );
                this.writeEndElement();
        },
        //add a text node wrapped with CDATA
        writeCDATA:function( text ){
                this.writeString( '<![CDATA[' + text + ']]>' );
        },
        //add a text node wrapped in a comment
        writeComment:function( text ){
                this.writeString('<!-- ' + text + ' -->');
        },
        //generate the xml string, you can skip closing the last nodes
        flush:function(){               
                if( this.stack && this.stack[0] )//ensure it's closed
                        this.writeEndDocument();
               
                var
                        chr = '', indent = '', num = this.indentation,
                        formatting = this.formatting.toLowerCase() == 'indented',
                        buffer = '<?xml version="'+this.version+'" encoding="'+this.encoding+'"';
                       
                        /*
                        *        modded by Phong Thai @ JavaScriptBank.com
                        */
                        buffer = buffer.replace( '?', '?' );
                       
                if( this.standalone !== undefined )
                        buffer += ' standalone="'+!!this.standalone+'"';
                buffer += ' ?>';
               
                buffer = [buffer];
               
                if( this.doctype && this.root )
                        buffer.push('<!DOCTYPE '+ this.root.n + ' ' + this.doctype+'>');
               
                if( formatting ){
                        while( num-- )
                                chr += this.indentChar;
                }
               
                if( this.root )//skip if no element was added
                        format( this.root, indent, chr, buffer );
               
                return buffer.join( formatting ? this.newLine : '' );
        },
        //cleanup, don't use again without calling startDocument
        close:function(){
                if( this.root )
                        clean( this.root );
                this.active = this.root = this.stack = null;
        },
        getDocument: window.ActiveXObject
                ? function(){ //MSIE
                        var doc = new ActiveXObject('Microsoft.XMLDOM');
                        doc.async = false;
                        doc.loadXML(this.flush());
                        return doc;
                }
                : function(){// Mozilla, Firefox, Opera, etc.
                        return (new DOMParser()).parseFromString(this.flush(),'text/xml');
        }
};

//utility, you don't need it
function clean( node ){
        var l = node.c.length;
        while( l-- ){
                if( typeof node.c[l] == 'object' )
                        clean( node.c[l] );
        }
        node.n = node.a = node.c = null;       
};

//utility, you don't need it
function format( node, indent, chr, buffer ){
        var
                xml = indent + '<' + node.n,
                nc = node.c.length,
                attr, child, i = 0;
               
        for( attr in node.a )
                xml += ' ' + attr + '="' + node.a[attr] + '"';
       
        xml += nc ? '>' : ' />';

        buffer.push( xml );
               
        if( nc ){
                do{
                        child = node.c[i++];
                        if( typeof child == 'string' ){
                                if( nc == 1 )//single text node
                                        return buffer.push( buffer.pop() + child + '</'+node.n+'>' );                                       
                                else //regular text node
                                        buffer.push( indent+chr+child );
                        }else if( typeof child == 'object' ) //element node
                                format(child, indent+chr, chr, buffer);
                }while( i < nc );
                buffer.push( indent + '</'+node.n+'>' );
        }
};

})();
</script>

Step 2: Place HTML below in your BODY section
HTML
Code:

<script type="text/javascript">
var xw = new XMLWriter('UTF-8');
xw.formatting = 'indented';//add indentation and newlines
xw.indentChar = ' ';//indent with spaces
xw.indentation = 2;//add 2 spaces per level

xw.writeStartDocument( );
xw.writeDocType('"items.dtd"');
xw.writeStartElement( 'items' );
       
        xw.writeComment('button');
        xw.writeStartElement('item');
                xw.writeAttributeString( 'id', 'item-1');
                xw.writeAttributeString( 'enabled', 'true' );
                xw.writeStartElement( 'code');
                        xw.writeCDATA( '<button>Save</button>' );
                xw.writeEndElement();
                xw.writeElementString('description', 'a save button');
        xw.writeEndElement();
       
        xw.writeComment('image');
        xw.writeStartElement('item');
                xw.writeAttributeString( 'id', 'item-2');
                xw.writeAttributeString( 'enabled', 'false' );
                xw.writeStartElement( 'code');
                        xw.writeCDATA( '<img src="photo.gif" alt="me" />' );
                xw.writeEndElement();
                xw.writeElementString('description', 'a pic of myself!');
        xw.writeEndElement();
       
        xw.writeComment('link');
        xw.writeStartElement('item');
                xw.writeAttributeString( 'id', 'item-3');
                xw.writeAttributeString( 'enabled', 'true' );
                xw.writeStartElement( 'code');
                        xw.writeCDATA( '<a href="http://google.com">Google</a>' );
                xw.writeEndElement();
                xw.writeElementString('description', 'a link to Google');
        xw.writeEndElement();
       
xw.writeEndElement();
xw.writeEndDocument();

var xml = xw.flush(); //generate the xml string
xw.close();//clean the writer
xw = undefined;//don't let visitors use it, it's closed
//set the xml
document.getElementById('parsed-xml').value = xml;
</script>







JavaScriptBank 04-25-2011 03:07 AM

Simple JavaScript Page-Note Glossary
 
If you ever seen many web pages, posts of professional knowledges, specialized in skills or researches; perhaps you would see many specialized in words that they're explained after each post/page.

... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Copy & Paste CSS code below in your HEAD section
CSS
Code:

<style type="text/css">
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/

dl.glossary:after {
  content: ".";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
dl.glossary dt {
  float: left;
  clear: left;
  margin: 0;
  padding: 0 0 5px;
}
dl.glossary dt:after {
  content: ":";
}
dl.glossary dd {
  float: left;
  clear: right;
  margin: 0 0 0 5px;
  padding: 0 0 5px;
}
* html dl.glossary dd {
  clear: none;
  width: 80%;
}
</style>

Step 2: Copy & Paste JavaScript code below in your HEAD section
JavaScript
Code:

<script type="text/javascript">
// Created by: Aaron Gustafson | http://www.easy-designs.net/
// This script downloaded from www.JavaScriptBank.com

// ---------------------------------------------------------------------
//                            onLoad Handler
// ---------------------------------------------------------------------
var old = window.onload; // catch any existing onload calls 1st
window.onload = function () {
  if (old) { // execute existing onloads
    old();
  };
  for (var ii = 0; arguments.callee.actions.length > ii; ii++) {
    arguments.callee.actions[ii]();
  };
};
window.onload.actions = [];


/*------------------------------------------------------------------------------
Object:        pageGlossary (formerly makeGlossary)
Author:        Aaron Gustafson (aaron at easy-designs dot net)
Creation Date:  27 November 2005
Version:        1.0
Homepage:      http://www.easy-designs.net/code/pageGlossary/
License:        Creative Commons Attribution-ShareAlike 2.0 License
                http://creativecommons.org/licenses/by-sa/2.0/
Note:          If you change or improve on this script, please let us know by
                emailing the author (above) with a link to your demo page.
------------------------------------------------------------------------------*/
var pageGlossary = {
  getFrom:  false,
  buildIn:  false,
  glossArr: [],
  usedArr:  [],
  init:    function( fromId, toId ){
    if( !document.getElementById ||
        !document.getElementsByTagName ||
        !document.getElementById( fromId ) ||
        !document.getElementById( toId ) ) return;
    pageGlossary.getFrom = document.getElementById( fromId );
    pageGlossary.buildIn = document.getElementById( toId );
    pageGlossary.collect();
    if( pageGlossary.usedArr.length < 1 ) return;
    pageGlossary.glossArr = pageGlossary.ksort( pageGlossary.glossArr );
    pageGlossary.build();
  },
  collect:  function(){
    var dfns  = pageGlossary.getFrom.getElementsByTagName('dfn');
    var abbrs = pageGlossary.getFrom.getElementsByTagName('abbr');
    var acros = pageGlossary.getFrom.getElementsByTagName('acronym');
    var arr = [];
    arr = arr.concat( dfns, abbrs, acros );
    if( ( arr[0].length == 0 ) &&
        ( arr[1].length == 0 ) &&
        ( arr[2].length == 0 ) ) return;
    var arrLength = arr.length;
    for( var i=0; i < arrLength; i++ ){
      var nestedLength = arr[i].length;
      if( nestedLength < 1 ) continue;
      for( var j=0; j < nestedLength; j++ ){
        if( !arr[i][j].hasChildNodes() ) continue;
        var trm = arr[i][j].firstChild.nodeValue;
        var dfn = arr[i][j].getAttribute( 'title' );
        if( !pageGlossary.inArray( trm, pageGlossary.usedArr ) ){
          pageGlossary.usedArr.push( trm );
          pageGlossary.glossArr[trm] = dfn;
        }
      }
    }
  },
  build:    function(){
    var h2 = document.createElement('h2');
    h2.appendChild( document.createTextNode( 'Page Glossary' ) );
    var dl = document.createElement('dl');
    dl.className = 'glossary';
    for( key in pageGlossary.glossArr ){
      var dt = document.createElement( 'dt' );
      dt.appendChild( document.createTextNode( key ) );
      dl.appendChild( dt );
      var dd = document.createElement('dd');
      dd.appendChild( document.createTextNode( pageGlossary.glossArr[key] ) );
      dl.appendChild( dd );
    }
    pageGlossary.buildIn.appendChild( h2 );
    pageGlossary.buildIn.appendChild( dl );
  },
  addEvent: function( obj, type, fn ){  // the add event function
    if (obj.addEventListener) obj.addEventListener( type, fn, false );
    else if (obj.attachEvent) {
      obj['e'+type+fn] = fn;
      obj[type+fn] = function() {
        obj['e'+type+fn]( window.event );
      };
      obj.attachEvent( 'on'+type, obj[type+fn] );
    }
  },
  ksort:    function( arr ){
    var rArr = [], tArr = [], n=0, i=0, el;
    for( el in arr ) tArr[n++] = el + '|' + arr[el];
    tArr = tArr.sort();
    var arrLength = tArr.length;
    for( var i=0; i < arrLength; i++ ){
      var x = tArr[i].split( '|' );
      rArr[x[0]] = x[1];
    }
    return rArr;
  },
  inArray:  function( needle, haystack ){
    var arrLength = haystack.length;
    for( var i=0; i < arrLength; i++ ){
      if( haystack[i] === needle ) return true;
    }
    return false;
  }
};

pageGlossary.addEvent(
  window, 'load', function(){
    pageGlossary.init('content','extras');
  }
);
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<div style="text-align: left; width: 70%;">

<div id="content">
<p>
Lorem ipsum <dfn title="A Web browser created by Microsoft">Internet Explorer</dfn> dolor sit amet, consectetuer adipiscing elit 18 <abbr title="kilobytes">kB</abbr>, sed diam nonummy nibh euismod tincidunt ut laoreet <acronym title="Hypertext Markup Language">HTML</acronym> dolore magna aliquam erat volutpat.</p>
</div>

<div id="extras">
<!--  The page glossary is built here  -->

</div>

<br /><br /><br /><b>Note</b>
<p>
In the last section of the script, the ids for the content and glossary are given, in this example they are 'content' and 'extras'. The script will process the abbreviations, acronyms, and definitions contained in the 'content' id and then place them within the 'extras' id.
</p>
</div>







JavaScriptBank 04-25-2011 03:43 AM

Cool Analog Clock with Raphael by Amazing Styles
 
Collect the JavaScript code examples for creating cool JavaScript clocks is one of jsB@nk's initial criteria; till to this... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: downloads
Files
Cool Analog Clock with Raphael by Amazing Styles.zip







JavaScriptBank 04-25-2011 09:22 PM

JavaScript Image Rotation script with CANVAS in HTML5
 
Rotating images is not new type of JavaScript effects because they were ever showed on jsB@nk through many JavaScript code examples:

- detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Benoit Asselin | http://www.ab-d.fr
// This script downloaded from www.JavaScriptBank.com

function rotate(p_deg) {
        if(document.getElementById('canvas')) {
                /*
                Ok!: Firefox 2, Safari 3, Opera 9.5b2
                No: Opera 9.27
                */
                var image = document.getElementById('image');
                var canvas = document.getElementById('canvas');
                var canvasContext = canvas.getContext('2d');
               
                switch(p_deg) {
                        default :
                        case 0 :
                                canvas.setAttribute('width', image.width);
                                canvas.setAttribute('height', image.height);
                                canvasContext.rotate(p_deg * Math.PI / 180);
                                canvasContext.drawImage(image, 0, 0);
                                break;
                        case 90 :
                                canvas.setAttribute('width', image.height);
                                canvas.setAttribute('height', image.width);
                                canvasContext.rotate(p_deg * Math.PI / 180);
                                canvasContext.drawImage(image, 0, -image.height);
                                break;
                        case 180 :
                                canvas.setAttribute('width', image.width);
                                canvas.setAttribute('height', image.height);
                                canvasContext.rotate(p_deg * Math.PI / 180);
                                canvasContext.drawImage(image, -image.width, -image.height);
                                break;
                        case 270 :
                        case -90 :
                                canvas.setAttribute('width', image.height);
                                canvas.setAttribute('height', image.width);
                                canvasContext.rotate(p_deg * Math.PI / 180);
                                canvasContext.drawImage(image, -image.width, 0);
                                break;
                };
               
        } else {
                /*
                Ok!: MSIE 6 et 7
                */
                var image = document.getElementById('image');
                switch(p_deg) {
                        default :
                        case 0 :
                                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
                                break;
                        case 90 :
                                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
                                break;
                        case 180 :
                                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
                                break;
                        case 270 :
                        case -90 :
                                image.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
                                break;
                };
               
        };
};

// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(function() {
        var image = document.getElementById('image');
        var canvas = document.getElementById('canvas');
        if(canvas.getContext) {
                image.style.visibility = 'hidden';
                image.style.position = 'absolute';
        } else {
                canvas.parentNode.removeChild(canvas);
        };
       
        rotate(0);
});
</script>

Step 2: Copy & Paste HTML code below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<p>
        rotate:
        <input type="button" value="0°" onclick="rotate(0);">

        <input type="button" value="90°" onclick="rotate(90);">
        <input type="button" value="180°" onclick="rotate(180);">
        <input type="button" value="-90°" onclick="rotate(-90);">
</p>
<p>
        <img id="image" src="http://www.javascriptbank.com/templates/jsb.V8/images/logo_jsbank.jpg" alt="">
        <canvas id="canvas"></canvas>
</p>







JavaScriptBank 04-25-2011 09:55 PM

Nice AJAX Effects for Messages Box using MooTools
 
This is very simple JavaScript code example but it can create an amazing message box effect with AJAX operations, bases on ... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Copy & Paste CSS code below in your HEAD section
CSS
Code:

<style type="text/css">
body{font-family:"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif; font-size:12px;}
#box {
        margin-bottom:10px;
        width: auto;
        padding:4px;
        border:solid 1px #DEDEDE;
        background: #FFFFCC;
        display:none;
}
</style>

Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript" src="mootools.js"></script>
<script type="text/javascript">
// Created by Antonio Lupetti | http://woork.blogspot.com
// This script downloaded from www.JavaScriptBank.com
window.addEvent('domready', function(){
        var box = $('box');
        var fx = box.effects({duration: 1000, transition: Fx.Transitions.Quart.easeOut});
       
        $('save_button').addEvent('click', function() {
                box.style.display="block";
                box.setHTML('Save in progress...');
               
                /* AJAX Request here... */
               
                fx.start({       
                        }).chain(function() {
                                box.setHTML('Saved!');
                                this.start.delay(1000, this, {'opacity': 0});
                        }).chain(function() {
                                box.style.display="none";
                                this.start.delay(0001, this, {'opacity': 1});
                        });
                });
        });
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

Press &quot;Save&quot;</p>
<div id="box"></div>
<input name="" type="text" /><input id="save_button" name="save_button" type="button" value="save"/>

Step 4: downloads
Files
mootools.js







JavaScriptBank 04-28-2011 01:06 PM

HTC-style JavaScript Countdown Timer with jQuery
 
If the JavaScript countdown timers are ever presented on jsB@nk still do not satisfy you:

- [URL="http://www.javascriptbank.com/cool-javascript-digital-countdown-with-jquery.html"]Cool JavaScri... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Copy & Paste CSS code below in your HEAD section
CSS
Code:

<link rel="stylesheet" type="text/css" href="style.css" />
Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script src="/javascript/jquery.js" type="text/javascript"></script>
<script src="jquery.countdown.packed.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('#countdown').countdown({until:$.countdown.UTCDate(-8, 2011,  1 - 1, 1), format: 'DHMS', layout:
'<div id="timer">' + '<hr />'+
        '<div id="timer_days" class="timer_numbers">{dnn}</div>'+
        '<div id="timer_hours" class="timer_numbers">{hnn}</div>'+
        '<div id="timer_mins" class="timer_numbers">{mnn}</div>'+
        '<div id="timer_seconds" class="timer_numbers">{snn}</div>'+
'<div id="timer_labels">'+
        '<div id="timer_days_label" class="timer_labels">days</div>'+
        '<div id="timer_hours_label" class="timer_labels">hours</div>'+
        '<div id="timer_mins_label" class="timer_labels">mins</div>'+
        '<div id="timer_seconds_label" class="timer_labels">secs</div>'+
'</div>'+                                                       
'</div>'                                         
});
});
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<div id="countdown"></div>
Step 4: must download files below
Files
countdown1.png
countdown2.png
jquery.countdown.packed.js
style.css







JavaScriptBank 05-10-2011 11:58 PM

So-Ticker: OOP JavaScript Dynamic Ticker with Typing-Styled
 
This JavaScript code example makes your detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: CSS below for styling thescript, place it into HEAD section
CSS
Code:

<style type="text/css">
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
#so_oTickerContainer {
        width:700px;
        margin:auto;
        font:1.0em verdana,arial;
        background-color:lightyellow;
        border-top:1px solid yellow;
        border-bottom:1px solid yellow;
}

#so_oTickerContainer h1 {
        font:bold 0.9em verdana,arial;
        margin:0;
        padding:0;
}
       
.so_tickerContainer {
        position:relative;
        margin:auto;
        width:700px;
        background-color:lightyellow;
        border-top:1px solid yellow;
        border-bottom:1px solid yellow;
}

#so_tickerAnchor, #so_oTickerContainer a {
        text-decoration:none;
        color:black;
        font:bold 0.7em arial,verdana;
        border-right:1px solid #000;
        padding-right:2px;
}

#so_oTickerContainer a {
        border-style:none;
}

#so_oTickerContainer ul {
        margin-top:5px;
}

#so_tickerDiv {
        display:inline;
        margin-left:5px;
}

#so_tickerH1 {
        font:bold 1.0em arial,verdana;
        display:inline;
}

#so_tickerH1 a {
        text-decoration:none;
        color:#000;
        padding-right:2px;
}

#so_tickerH1 a img {
        border-style:none;
}

</style>

Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Created by: Steve Chipman | http://slayeroffice.com/

/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/


/****************************

so_ticker
version 1.0
last revision: 03.30.2006
steve@slayeroffice.com

For implementation instructions, see:
http://slayeroffice.com/code/so_ticker/

Should you improve upon or modify this
code, please let me know so that I can update
the version hosted at slayeroffice.

Please leave this notice intact.


****************************/

so_ticker = new Object();
so_ticker = {
        current:0,                       
        currentLetter:0,       
        zInterval:null,       
        tObj: null,                       
        op:0.95,                       
        pause: false,               
        tickerContent: [],       
        LETTER_TICK:100,
        FADE: 10,
        NEXT_ITEM_TICK: 3000,
        init:function() {
                var d=document;       
                var mObj = d.getElementById("so_oTickerContainer");       
                so_ticker.tObj = d.createElement("div");               
                so_ticker.tObj.setAttribute("id","so_tickerDiv");
                var h = d.createElement("h1");       
                h.appendChild(d.createTextNode(so_ticker.getTextNodeValues(mObj.getElementsByTagName("h1")[0])));       
                h.setAttribute("id","so_tickerH1");       
                var ea = d.createElement("a");
                ea.setAttribute("href","javascript:so_ticker.showContent();");
                pImg = ea.appendChild(document.createElement("img"));
                pImg.setAttribute("src","plus.png");
                pImg.setAttribute("alt","Click to View all News Items.");
                ea.setAttribute("title","Click to View all News Items.");
                h.insertBefore(ea,h.firstChild);
                anchors = mObj.getElementsByTagName("a");               
                var nObj = mObj.cloneNode(false);               
                mObj.parentNode.insertBefore(nObj,mObj);
                mObj.style.display = "none";       
                nObj.className = "so_tickerContainer";       
                nObj.setAttribute("id","so_nTickerContainer");
                nObj.appendChild(h);       
                nObj.appendChild(so_ticker.tObj);       
                so_ticker.getTickerContent();       
                so_ticker.zInterval = setInterval(so_ticker.tick,so_ticker.LETTER_TICK);       
        },
        showContent:function() {
                        var d = document;
                        d.getElementById("so_oTickerContainer").style.display = "block";
                        d.getElementById("so_nTickerContainer").style.display = "none";
                        d.getElementById("so_oTickerContainer").getElementsByTagName("a")[0].focus();
                        clearInterval(so_ticker.zInterval);
        },
        getTickerContent:function() {
                for(var i=0;i<anchors.length;i++) so_ticker.tickerContent[i] = so_ticker.getTextNodeValues(anchors[i]);
        },
        getTextNodeValues:function(obj) {
                if(obj.textContent) return obj.textContent;
                if (obj.nodeType == 3) return obj.data;
                var txt = [], i=0;
                while(obj.childNodes[i]) {
                        txt[txt.length] = so_ticker.getTextNodeValues(obj.childNodes[i]);
                        i++;
                }
            return txt.join("");
    },
    tick: function() {
            var d = document;
            if(so_ticker.pause) {
                    try {
                            so_ticker.clearContents(d.getElementById("so_tickerAnchor"));
                            d.getElementById("so_tickerAnchor").appendChild(d.createTextNode(so_ticker.tickerContent[so_ticker.current]));
                            so_ticker.currentLetter = so_ticker.tickerContent[so_ticker.current].length;
                    } catch(err) { }
                    return;
            }
            if(!d.getElementById("so_tickerAnchor")) {
                    var aObj = so_ticker.tObj.appendChild(d.createElement("a"));
                    aObj.setAttribute("id","so_tickerAnchor");
                    aObj.setAttribute("href",anchors[so_ticker.current].getAttribute("href"));
                    aObj.onmouseover = function() { so_ticker.pause = true; }
                    aObj.onmouseout = function() { so_ticker.pause = false; }
                    aObj.onfocus = aObj.onmouseover;
                        aObj.onblur = aObj.onmouseout;
                        aObj.setAttribute("title",so_ticker.tickerContent[so_ticker.current]);
            }
                d.getElementById("so_tickerAnchor").appendChild(d.createTextNode(so_ticker.tickerContent[so_ticker.current].charAt(so_ticker.currentLetter)));
            so_ticker.currentLetter++;
            if(so_ticker.currentLetter > so_ticker.tickerContent[so_ticker.current].length) {
                    clearInterval(so_ticker.zInterval);
                    setTimeout(so_ticker.initNext,so_ticker.NEXT_ITEM_TICK);
            }
    },
    fadeOut: function() {
            if(so_ticker.paused) return;
            so_ticker.setOpacity(so_ticker.op,so_ticker.tObj);
            so_ticker.op-=.10;
            if(so_ticker.op<0) {
                    clearInterval(so_ticker.zInterval);
                    so_ticker.clearContents(so_ticker.tObj);
                    so_ticker.setOpacity(.95,so_ticker.tObj);
                    so_ticker.op = .95;
                    so_ticker.zInterval = setInterval(so_ticker.tick,so_ticker.LETTER_TICK);
            }
    },
    initNext:function() {
                    so_ticker.currentLetter = 0, d = document;
                    so_ticker.current = so_ticker.tickerContent[so_ticker.current + 1]?so_ticker.current+1:0;
                    d.getElementById("so_tickerAnchor").setAttribute("href",anchors[so_ticker.current].getAttribute("href"));
                    d.getElementById("so_tickerAnchor").setAttribute("title",so_ticker.tickerContent[so_ticker.current]);
                    so_ticker.zInterval = setInterval(so_ticker.fadeOut,so_ticker.FADE);
    },
    setOpacity:function(opValue,obj) {
            obj.style.opacity = opValue;
            obj.style.MozOpacity = opValue;
            obj.style.filter = "alpha(opacity=" + (opValue*100) + ")";
    },
    clearContents:function(obj) {
            try {
                    while(obj.firstChild) obj.removeChild(obj.firstChild);
            } catch(err) { }
    }
}


function page_init(){
        so_ticker.init();
}
window.addEventListener?window.addEventListener("load",page_init,false):window.attachEvent("onload",page_init);
</script>

Step 3: Place HTML below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->

        <div id="so_oTickerContainer">
                <h1>Latest News:</h1>
                <ul>
                        <li><a href="http://slayeroffice.com" rel="nofollow">Cat reported to have secured a fiddle.</a></li>
                        <li><a href="http://centricle.com" rel="nofollow">Cows: Able to leap orbiting satellites?</a></li>
                        <li><a href="http://adactio.com" rel="nofollow">People alarmed to hear small dog laughing.</a></li>
                        <li><a href="http://steve.ganz.name/blog/" rel="nofollow">Fork devastated as Spoon runs off with Dish.</a></li>

                </ul>
        </div>

Step 4: Download files below
Files
plus.png







JavaScriptBank 05-11-2011 12:39 AM

Colours-on-Page Displaying with MooTools
 
When users click a specified button, this JavaScript code example will get colours of all HTML elements with the predefined color attributes then fill those colours into many tiny rectangles. The auth... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: CSS below for styling thescript, place it into HEAD section
CSS
Code:

<style type="text/css">
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/

.dcolor  {
  height:40px;
}

.dtext {
  }

.dwrapper {
  width:100px;
  float:left;
  padding:10px;
  margin:0 20px 20px 0;
  border:1px solid #ccc;
}
</style>

Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript" src="/javascript/mootools.js"></script>
<script type="text/javascript">
// Created by: David Walsh | http://eriwen.com/css/color-palette-with-css-and-moo/
// This script downloaded from www.JavaScriptBank.com

//once the dom is ready
window.addEvent('domready', function() {

        //do it!
        $('get-colors').addEvent('click', function() {
                //starting the colors array
                var colors = [];
                var disallows = ['transparent'];

                //for every element
                $$('*').each(function(el) {
                        //record colors!
                        colors.include(el.getStyle('color'));
                        colors.include(el.getStyle('background-color'));
                        el.getStyle('border-color').split(' ').each(function(c) {
                                colors.include(c);
                        });
                });

                //sort the colors
                colors.sort();

                //empty wrapper
                $('colors-wrapper').empty();

                //for every color...
                colors.each(function(val,i) {

                        //if it's good
                        if(!disallows.contains(val))
                        {

                                //create wrapper div
                                var wrapper = new Element('div', {
                                        'class':'dwrapper'
                                });

                                //create color div, inject
                                var colorer = new Element('div', {
                                        'class':'dcolor',
                                        'style': 'background:' + val
                                });
                                colorer.inject(wrapper);

                                //alert(val);

                                //create text div, inject
                                var texter = new Element('div', {
                                        'class':'dtext',
                                        'text':val
                                });
                                texter.inject(wrapper);

                                //inject wrapper
                                wrapper.inject($('colors-wrapper'));
                        }
                });
        });
});
</script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<input type="button" id="get-colors" value="Get Colors" class="button">
<br><br><br>
<div id="colors-wrapper"></div>

<br clear="all">

<div style="text-align: left; width: 70%;">
<p>
Ma quande lingues coalesce. <span style="color: #279F37;">Li nov lingua franca va esser</span> plu simplic e regulari. Lorem ipsum dolor sit amet, <span style="color: #9F6827;">consectetuer adipiscing elit, sed diam nonummy</span> nibh euismod tincidunt ut <span style="color: #BFB00B;">laoreet dolore magna aliquam erat volutpat</span>.</p>

</div>

Step 4: must download files below
Files
mootools.js







JavaScriptBank 05-11-2011 01:13 AM

Tick Tock: Amazing Analog Clock with CSS
 
This JavaScript code example will create a super beautiful analog clock with amazing layout on your web pages. However, this [URL="http://www.javascriptbank.com/dhtml-analog-clock-ii.html"]JavaScri... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: CSS below for styling thescript, place it into HEAD section
CSS
Code:

<style type="text/css">
        #clockbase {
                width: 512px;
                height: 512px;
                position: relative;
                margin: 0 auto;
                background: url(clock_bg.jpg) no-repeat;
        }
        #minutes {
                width: 229px;
                height: 229px;
                position: absolute;
                top: 200px;
                left: 137px;
                background: url(minutes-arm.png) no-repeat;
        }
        #hours {
                width: 200px;
                height: 200px;
                position: absolute;
                top: 220px;
                left: 150px;
                background: url(hours-arm.png) no-repeat left bottom;
        }
        #seconds {
                width: 260px;
                height: 260px;
                position: absolute;
                top: 184px;
                left: 120px;
                background: url(SECS.gif) no-repeat;
               
        }
        #clockbase .min05 {background-position: left top;}
        #clockbase .min10 {background-position: left -229px;}
        #clockbase .min15 {background-position: left -458px;}
        #clockbase .min20 {background-position: left -687px;}
        #clockbase .min25 {background-position: left -916px;}
        #clockbase .min30 {background-position: left -1145px;}
        #clockbase .min35 {background-position: left -1374px;}
        #clockbase .min40 {background-position: left -1603px;}
        #clockbase .min45 {background-position: left -1832px;}
        #clockbase .min50 {background-position: left -2061px;}
        #clockbase .min55 {background-position: left -2290px;}
        #clockbase .min00 {background-position: left -2519px;}
       
        #clockbase .hr1 {background-position: left top;}
        #clockbase .hr2 {background-position: left -200px;}
        #clockbase .hr3 {background-position: left -400px;}
        #clockbase .hr4 {background-position: left -600px;}
        #clockbase .hr5 {background-position: left -800px;}
        #clockbase .hr6 {background-position: left -1000px;}
        #clockbase .hr7 {background-position: left -1200px;}
        #clockbase .hr8 {background-position: left -1400px;}
        #clockbase .hr9 {background-position: left -1600px;}
        #clockbase .hr10 {background-position: left -1800px;}
        #clockbase .hr11 {background-position: left -2000px;}
        #clockbase .hr12 {background-position: left -2200px;}
       
        *html #minutes {
                background: url(minutes-arm.gif) no-repeat;
        }
        *html #hours {
                background: url(hours-arm.gif) no-repeat left bottom;
        }
        </style>

Step 2: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript" language="javascript">
                var g_nLastTime = null;
               
                function cssClock(hourElementId, minuteElementId)
                {
                        // Check if we need to do an update
                        var objDate = new Date();
                        if(!g_nLastTime || g_nLastTime.getHours() > objDate.getHours() || g_nLastTime.getMinutes() <= (objDate.getMinutes() - 5))
                        {
                                // make sure parameters are valid
                                if(!hourElementId || !minuteElementId) { return; }

                                // get the element objects
                                var objHour = document.getElementById(hourElementId);
                                var objMinutes = document.getElementById(minuteElementId);
                                if (!objHour || !objMinutes) { return; }

                                // get the time
                                var nHour = objDate.getHours();
                                if (nHour > 12) { nHour -= 12; }  // switch from 24-hour to 12-hour system
                                var nMinutes = objDate.getMinutes();

                                // round the time
                                var nRound = 5;
                                var nDiff = nMinutes % nRound;
                                if(nDiff != 0)
                                {
                                        if (nDiff < 3) { nMinutes -= nDiff; } // round down
                                        else { nMinutes += nRound - nDiff; } // round up
                                }
                                if(nMinutes > 59)
                                {
                                        // handle increase the hour instead
                                        nHour++;
                                        nMinutes = 0;
                                }

                                // Update the on page elements
                                objHour.className = 'hr' + nHour;
                                objMinutes.className = 'min' + nMinutes;

                                // Timer to update the clock every few minutes
                                g_nLastTime = objDate;
                        }

                        // Set a timer to call this function again
                        setTimeout(function() { cssClock(hourElementId, minuteElementId); }, 60000); // update the css clock every minute (or so)
                }
        </script>

Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:

<div id="clockbase">
            <div class="hr10" id="hours"></div>
            <div class="min10" id="minutes"></div>
                <div id="seconds"></div>
        </div>
        <script type="text/javascript" language="javascript">
        cssClock('hours', 'minutes');
        </script>

Step 4: downloads
Files
clock_bg.jpg
hours-arm.gif
hours-arm.png
minutes-arm.gif
minutes-arm.png
SECS.gif







JavaScriptBank 05-30-2011 09:35 PM

Simulate Awesome Flash Horizontal Navigation with MooTools
 
A very great JavaScript code example to simulate Flash effects in this script: the users move mouse pointer to the edges of content div then all remaining ... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup







JavaScriptBank 06-16-2011 08:03 PM

Simple JavaScript Slideshow in 2 code lines with jQuery
 
In this post, jsB@nk is happy to present to you a tiny JavaScript slideshow effect made by 2 code lines. It's so very simple and easy to implement but its JavaScript animations are so great to apply o... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: must download files below
Files
1.html
2.html
3.html
jquery-1.4.3.js







JavaScriptBank 06-16-2011 10:01 PM

Simple JavaScript RegEx to Parse Domain Name
 
There are many JavaScript resources to parse an URL in JavaScript RegEx. And parsing the domain main is easy since there's a lot of trick. This is useful f... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Use JavaScript code below to setup the script
JavaScript
Code:

<script type="text/javascript">
// Copyright: ivanceras - http://www.ivanceras.com/
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/

/**
 *
 * USAGE:
 * UriParser.parseRootDomain("http://user:password@www.truste.com.ca:80/pathname?querystring&key=value#fragment"); //= truste.com.ca
 * UriParser.parseRootDomain("http://google.com.ph/pathname?querystring&key=value#fragment"); //= google.com.ph
 * UriParser.parseRootDomain("http://www.google.com/pathname?querystring&key=value#fragment"); //= google.com
 *
 */
var UriParser =  {

 //parse the root domain, exclude the sub domain
 parseRootDomain : function(url) {
  var matches = url.match(/^((\w+):\/\/)?((\w+):?(\w+)?@)?([^\/\?:]+):?(\d+)?(\/?[^\?#]+)?\??([^#]+)?#?(\w*)/);
 
  //my additional code
  var theDomain = matches[6];
 
  if(UriParser.isIp(theDomain)){//if it is an ip address return it as domain
  return theDomain;
  }
  var dots = theDomain.split('.');
  var n = dots.length;
 
  if(n < 3){//google.com, 2 root words concatenate, 1 word as well i.e. localhost
  return dots.join(".");
  }
  else{//should be greater than or equal to 3 dot split ie. adsense.google.com
  var last = dots[n-1];
  var second2l = dots[n-2];
  var third2l = dots[n-3];
 
  var ext;
  var root;
  if(second2l.length <= 3){//if google.com.ph, or bbc.co.uk
    ext = second2l +"."+ last;
    root = third2l;
  }else{// adsense.google.com
    ext = last;
    root = second2l;
  }
  var domain = ""+ root + "." + ext;
  return domain;
  }
 },
 
 //private
 isNumber : function (o) {
    return !isNaN (o-0);
 },
 //private
 /**
  * determines if the url is an ip address
  */
 isIp: function(domain){
  var exploded = domain.split('.');
  for(var i = 0; i < exploded.length; i++){
  if(!UriParser.isNumber(exploded[i])){
    return false;
  }
  }
  return true;
 },
 
 isSameDomain: function(url1, url2){
  if(UriParser.parseRootDomain(url1) == UriParser.parseRootDomain(url2)){
  return true;
  }
  return false;
 }

}
</script>

Step 2: Copy & Paste HTML code below in your BODY section
HTML
Code:

<h3>Usages:</h3>
document.write(UriParser.parseRootDomain("http://user:password@www.truste.com.ca:80/pathname?querystring&key=value#fragment"));<br />
document.write(UriParser.parseRootDomain("http://google.com.ph/pathname?querystring&key=value#fragment"));<br />
document.write(UriParser.parseRootDomain("http://www.google.com/pathname?querystring&key=value#fragment"));<br />
document.write(UriParser.parseRootDomain("http://google.com/pathname?querystring&key=value#fragment"));<br />
document.write(UriParser.parseRootDomain("http://localhost/pathname?querystring&key=value#fragment"));<br />
document.write(UriParser.parseRootDomain("localhost"));<br />
document.write(UriParser.parseRootDomain("http://192.168.1.1/pathname?querystring&key=value#fragment"));<br />
document.write(UriParser.isSameDomain("http://www.google.com/pathname?querystring&key=value#fragment", "http://adsense.google.com/?x=123123"))
document.write(UriParser.isSameDomain("http://www.blogger.com/navbar.g?targetBlogID=5856931630868336061&blogName=TeamPilipinas.info&publishMode=PUBLISH_MODE_HOSTED&navbarType=BLACK&layoutType=LAYOUTS&searchRoot=http%3A%2F%2Fteampilipinas.info%2Fsearch&blogLocale=en_PH&homepageUrl=http%3A%2F%2Fteampilipinas.info%2F", "blogger.com"));<br />
<hr />
<h3>Results:</h3>
<script type="text/javascript">
document.write(UriParser.parseRootDomain("http://user:password@www.truste.com.ca:80/pathname?querystring&key=value#fragment") + '<br />');
document.write(UriParser.parseRootDomain("http://google.com.ph/pathname?querystring&key=value#fragment") + '<br />');
document.write(UriParser.parseRootDomain("http://www.google.com/pathname?querystring&key=value#fragment") + '<br />');
document.write(UriParser.parseRootDomain("http://google.com/pathname?querystring&key=value#fragment") + '<br />');
document.write(UriParser.parseRootDomain("http://localhost/pathname?querystring&key=value#fragment") + '<br />');
document.write(UriParser.parseRootDomain("localhost") + '<br />');
document.write(UriParser.parseRootDomain("http://192.168.1.1/pathname?querystring&key=value#fragment") + '<br />');
document.write(UriParser.isSameDomain("http://www.google.com/pathname?querystring&key=value#fragment", "http://adsense.google.com/?x=123123"))
document.write(UriParser.isSameDomain("http://www.blogger.com/navbar.g?targetBlogID=5856931630868336061&blogName=TeamPilipinas.info&publishMode=PUBLISH_MODE_HOSTED&navbarType=BLACK&layoutType=LAYOUTS&searchRoot=http%3A%2F%2Fteampilipinas.info%2Fsearch&blogLocale=en_PH&homepageUrl=http%3A%2F%2Fteampilipinas.info%2F", "blogger.com"));
</script>







JavaScriptBank 06-16-2011 10:35 PM

Snake Game in JavaScript & YUI
 
There are already many versions of snake classic games available on the Internet. Now this Snake game was just some fun ... detail at JavaScriptBank.com - 2.000+ free JavaScript codes


How to setup

Step 1: Place CSS below in your HEAD section
CSS
Code:

<style type="text/css">
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
body {
    background-color:#EEF3E2;
    margin:0;
    padding:0;
    font:13px arial;
}
#arena {
    border:1px solid #000;
    width:644px;
    height:444px;
    margin:20px 0 0 24px;
    float:left;
}
#info {
    float:left;
    margin:20px 0 0 40px;
}
#info ul {
    margin-left:0;
    padding-left:16px;
}
#info #title {
    color:#228B22;
    font-size:20px;
}
#info #instructions ul#colorCodes {
    padding:0;
}
#info #instructions #colorCodes li {
    list-style-type:none;
}
#info #instructions #colorCodes span {
    width:14px;
    height:12px;
    display:inline-block;
    color:#FFF;
    margin-right:4px;
}
#info #instructions #colorCodes span.foodColor {
    background-color:#228B22;
}
#info #instructions #colorCodes span.bonusColor {
    background-color:#FFB90F;
}
#info #score {
    border:0px solid #000;
    width:100px;
    height:20px;
    margin-top:20px;
    color:#8B4513;
    font-weight:bold;
    font-size:15px;
}
#info #addninfo {
    margin-top:20px;
    font-size:12px;
    font-style:italic;
}
.cell {
    border:0px solid #000;
    width:14px;
    height:12px;
    background-color: #FFF;
    float:left;

.clear {
    clear:both;
}
</style>
<link rel="stylesheet" type="text/css" href="container.css">

Step 2: Place JavaScript below in your HEAD section
JavaScript
Code:

<script src="yahoo-dom-event.js"></script>
<script src="container-min.js"></script>
<script src="snake.js"></script>

Step 3: Place HTML below in your BODY section
HTML
Code:

<!--
/*
    This script downloaded from www.JavaScriptBank.com
    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<body class="yui-skin-sam">
    <div id="wrapper">
        <div id="arena"></div>
        <div id="info">
            <div id="title">SNAKE</div>
            <div id="score">Score: <i>0</i></div>
            <div id="instructions">

                <ul>
                    <li>Press ARROW keys to move the snake.</li>
                    <li>Press P to pause or resume.</li>
                    <li>Earlier you eat the food, more points you get.</li>
                    <li>Snake gets killed if it collides with the walls or its own body.</li>
                    <li>Color codes:
                        <ul id=colorCodes>

                            <li><span class=foodColor></span>Food (Max 250 points, length increases by 4 units)</li>
                            <li><span class=bonusColor></span>Bonus (500 points, disappears if not eaten within 10 seconds)</li>
                        </ul>
                    </li>
                </ul>
            </div>
            <div id=credits>
                This game is created in Javascript using YUI 2 framework.
                </br>

                Author: <a href="http://odhyan.com">Saurabh Odhyan</a>
                </br>
            </div>
            <div id="addninfo">
                Works well on FF, Chrome and Safari. Didn't have the patience to debug on IE.
            </div>
        </div>
        <div class="clear"></div>

    </div>
</body>

Step 4: downloads
Files
container-min.js
container.css
snake.js
yahoo-dom-event.js








All times are GMT -5. The time now is 11:17 AM.

Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2025, Jelsoft Enterprises Ltd.
HTML Help provided by HTML Help Central.