-
Awesome jQuery Accordion with CSS3 and HTML5
This JavaScript-jQuery code example is suitable for websites with a huge list of categories (divided into subjects) need to be showed. This detail at JavaScriptBank.com - 2.000+ free JavaScript codes
How to setup
Step 1: Place CSS below in your HEAD section
CSS
Code:
<link rel='stylesheet' type='text/css' href='css/style.css' />
Step 2: Copy & Paste JavaScript code below in your HEAD section
JavaScript
Code:
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'></script>
<script type='text/javascript' src='js/infogrid.js'></script>
Step 3: Place HTML below in your BODY section
HTML
Code:
<div id="page-wrap">
<div class="info-col">
<h2>Superman</h2>
<a class="image superman" href="http://jprart.deviantart.com/art/Batman-and-Superman-64545242">View Image</a>
<dl>
<dt>Super Power</dt>
<dd><a href="http://css-tricks.com">Consectetur</a> adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Costume</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Morality</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Sidekicks</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Vehicles</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Weaknesses</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
</dl>
</div>
<div class="info-col">
<h2>Batman</h2>
<a class="image batman" href="http://jprart.deviantart.com/">View Image</a>
<dl>
<dt>Super Power</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Costume</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Morality</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Sidekicks</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Vehicles</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Weaknesses</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
</dl>
</div>
<div class="info-col">
<h2>Aquaman</h2>
<a class="image aquaman" href="http://www.deviantart.com/print/8342014/">View Image</a>
<dl>
<dt id="starter">Super Power</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Costume</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Morality</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Sidekicks</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Vehicles</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Weaknesses</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
</dl>
</div>
<div class="info-col">
<h2>Spiderman</h2>
<a class="image spiderman" href="http://eldelgado.deviantart.com/">View Image</a>
<dl>
<dt>Super Power</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Costume</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Morality</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Sidekicks</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Vehicles</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Weaknesses</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
</dl>
</div>
<div class="info-col">
<h2>Ironman</h2>
<a class="image ironman" href="http://diablo2003.deviantart.com/">View Image</a>
<dl>
<dt>Super Power</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Costume</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Morality</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Sidekicks</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Vehicles</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
<dt>Weaknesses</dt>
<dd>Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat.</dd>
</dl>
</div>
</div>
Step 4: Download files below
Files
Awesome jQuery Accordion with CSS3 and HTML5.zip
-
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: Use CSS code below for styling the script
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: Use JavaScript code below to setup the script
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: Download files below
Files
jquery.js
image-1.jpg
image-2.jpg
image-3.jpg
image-4.jpg
-
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
-
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>
-
-
Powerful JavaScript OOP for HTML Scroller
The powers jsB@nk would like to tell in this JavaScript text scroller are JavaScript OOP skills, this [URL="http://www.javascriptbank.com/=news scroller JavaScript"]news scroller JavaSc... 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">
#scr1 div {
visibility:hidden;
}
#scr1, #scr1 div.default {
width:160px;
height:120px;
overflow:hidden;
visibility:visible;
}
#scr1 table tr td div {
visibility:visible;
}
#scr1 {
background-color:#fff;
margin:0px auto;
font-size: .8em;
}
</style>
Step 2: Place JavaScript below in your HEAD section
JavaScript
Code:
<script type="text/javascript">
// Created by: Brian Huisman | http://www.greywyvern.com/
// This script downloaded from www.JavaScriptBank.com
/* ********************************************************************
* HTML Block Scroller & Marquee JavaScript - v2.0
* - Copyright 2008 - Licenced for free distribution under the BSDL
* - http://www.opensource.org/licenses/bsd-license.php
*
* Have one or more scrolling blocks of HTML anywhere on your webpages.
* The scroller will even pause on mouseover and resume on mouseout.
*
* Version 2.0
* - Uses DOM-only methods (compatible with application/xhtml+xml)
* - Blocks are created in the HTML page, rather than as JS variables
* - Automatic startup on page load
***********************************************************************
*** Instructions ******************************************************
***********************************************************************
* 1. Create the container for the scroller in the body of your HTML:
*
* <div id="scr1"></div>
*
* Where "scr1" is any name you choose. You don't have to use a <div>
* either. You may use any block level element that can be pixel
* resized; such as a <span> element to which the display:block; CSS
* property has been applied.
*
***********************************************************************
* 2. Fill the scroller container with child <div> blocks:
*
* <div id="scr1">
* <div class="default">
* The contents of this block will be displayed if the browser does
* not support the scroller.
* It will be overwritten if the scroller is supported.
* </div>
* <div>Block 2</div>
* <div>Block 3</div>
*
* ...
*
* </div>
*
* Assign the class "default" to the first block, the one which you
* would like displayed if javascript is disabled.
*
***********************************************************************
* 3. Add the following rule(s) to your CSS stylesheet:
*
* #scr1 div {
* visibility:hidden;
* }
* #scr1, #scr1 div.default {
* width:160px;
* height:120px;
* overflow:hidden;
* visibility:visible;
* }
* #scr1 table tr td div {
* visibility:visible;
* }
*
* Change both "scr1" to the id you gave to the scroller container. The
* width and height properties should match those you will use in step 4.
*
* To further style the scroller container, assign CSS properties to the
* scroller target id:
*
* #scr1 {
* background-color:#f6f6f6;
* margin:0px auto;
* }
*
* The script will replace each block you add to the container with a
* single-celled <table>. So to style the blocks of your scroller, you
* can style these table cells as if they were actually part of your
* document source:
*
* #scr1 table tr td {
* padding:10px;
* color:#ff0000;
* text-align:center;
* vertical-align:middle;
* }
*
***********************************************************************
* 4. Create a new scrollObject:
*
* new scrollObject("scr1", 120, 120, "up", 5000, 1.4);
*
* The arguments for this object are as follows:
* a. - ID of the target tag (from step 1)
* b. - Width (in pixels) of your scroller
* c. - Height (in pixels) of your scroller
* d. - Scroll direction: one of "up", "down", "left" or "right"
* e. - Amount of time to pause before next scroll begins (ms)
* f. - Slide-in speed of your scroller (1.001 up to width or height)
*
***********************************************************************
*** To add more scrollers to the same page: ***************************
***********************************************************************
* 1. Create additional containers - with different ID's - and blocks in
* the body of your HTML
*
* <div id="scr2">
* <div class="default"><strong>HTML is allowed too!</strong></div>
* <div><img src="/images/mybanner.jpg" alt=""></div>
* <div><a href="/home">And links!</a></div>
* <div>As long as it fits within the dimensions above</div>
* </div>
*
* <div id="scr3">
* <div class="default">Block 1</div>
* <div>Block 2</div>
* <div>Block 3</div>
* <div>Block 4</div>
* </div>
*
***********************************************************************
* 2. Add the matching rules to your CSS stylesheet
*
* #scr2 div,
* #scr3 div {
* visibility:hidden;
* }
* #scr2, #scr2 div.default {
* width:468px;
* height:60px;
* overflow:hidden;
* visibility:visible;
* }
* #scr3, #scr3 div.default {
* width:140px;
* height:140px;
* overflow:hidden;
* visibility:visible;
* }
* #scr2 table tr td div,
* #scr3 table tr td div {
* visibility:visible;
* }
*
***********************************************************************
* 3. Create new scrollObjects for each scroller in the <script> tag:
*
* new scrollObject("scr2", 468, 60, "down", 10000, 1.2);
* new scrollObject("scr3", 140, 140, "right", 4000, 2);
*
***********************************************************************
*** End Instructions **************************************************
*************************************************** BEGIN CODE ***** */
/* *****
* See http://www.greywyvern.com/code/js/scroller.html for the page
* which uses the example scrollers below
*
*/
// ***** Start scroller #1
new scrollObject("scr1", 160, 120, "up", 5000, 1.15);
// ***** Start scroller #2
new scrollObject("scr2", 468, 60, "left", 3000, 1.5);
/* ********************************************************************
* The Mighty ScrollObject
* - Don't edit this if you know what's good for ya!
*
*/
function scrollObject(main, width, height, direct, pause, speed) {
var self = this;
this.main = main;
this.width = width;
this.height = height;
this.direct = direct;
this.pause = pause;
this.speed = Math.max(1.001, Math.min((direct == "up" || direct == "down") ? height : width, speed));
this.slope = (direct == "up" || direct == "left") ? 1 : -1;
this.prev = this.offset = 0;
this.curr = 1;
this.mouse = false;
this.scroll = function() {
this.main = document.getElementById(this.main);
this.main.style.overflow = "hidden";
this.main.style.position = "relative";
this.main.style.width = this.width + "px";
this.main.style.height = this.height + "px";
var b = [], c;
while (this.main.firstChild) if ((c = this.main.removeChild(this.main.firstChild)).nodeName == "DIV") b.push(c);
for (var x = 0; x < b.length; x++) {
var table = document.createElement('table');
table.cellPadding = table.cellSpacing = table.border = "0";
table.style.position = "absolute";
table.style.left = table.style.top = "0px";
table.style.width = table.style.height = "100%";
table.style.overflow = table.style.visibility = "hidden";
var tbody = document.createElement('tbody');
var tr = document.createElement('tr');
var td = document.createElement('td');
while (b[x].firstChild)
td.appendChild(b[x].removeChild(b[x].firstChild));
tr.appendChild(td);
tbody.appendChild(tr);
table.appendChild(tbody);
this.main.appendChild(table);
} b = c = null;
if (this.main.childNodes.length > 1) {
this.main.onmouseover = function() { self.mouse = true; };
this.main.onmouseout = function() { self.mouse = false; };
setInterval(function() {
if (!self.offset && self.scrollLoop()) self.main.childNodes[self.curr].style.visibility = "visible";
}, this.pause);
} this.main.childNodes[this.prev].style.visibility = "visible";
};
this.scrollLoop = function() {
if (!this.offset) {
if (this.mouse) return false;
this.offset = (this.direct == "up" || this.direct == "down") ? this.height : this.width;
} else this.offset = Math.floor(this.offset / this.speed);
if (this.direct == "up" || this.direct == "down") {
this.main.childNodes[this.curr].style.top = (this.offset * this.slope) + "px";
this.main.childNodes[this.prev].style.top = ((this.offset - this.height) * this.slope) + "px";
} else {
this.main.childNodes[this.curr].style.left = (this.offset * this.slope) + "px";
this.main.childNodes[this.prev].style.left = ((this.offset - this.width) * this.slope) + "px";
}
if (!this.offset) {
this.main.childNodes[this.prev].style.visibility = "hidden";
this.prev = this.curr;
if (++this.curr >= this.main.childNodes.length) this.curr = 0;
} else setTimeout(function() { self.scrollLoop(); }, 30);
return true;
};
if (window.addEventListener) {
window.addEventListener('load', function() { self.scroll(); }, false);
} else if (window.attachEvent)
window.attachEvent('onload', function() { self.scroll(); });
}
</script>
Step 3: Place HTML below in your BODY section
HTML
Code:
<div id="scr1">
<div class="default"><i>The JavaScript Bank</i> is an excellent JavaScript resource.</div>
<div><b>Want some recognition for your scripts?</b><br><a href="http://javascriptbank.com/submit/">Submit them to us</a> and they can be featured on JavaScript Source!</div>
<div>Three times a week we add a new script or tutorial to our archives.</div>
</div>
-
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
-
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: Download files below
Files
Random of Testimonial Bubbles with XML and jQuery.zip
-
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: Copy & Paste CSS code below in your HEAD section
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>
-
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: downloads
Files
JavaScript Loading Progress Effect with jQuery.zip
-
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: 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
*/
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: 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 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>
-
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: downloads
Files
Cool JavaScript Digital Countdown with jQuery.zip
-
JavaScript Multi-level Navigation Menu with States-Remember
This JavaScript code example will create a multi-level navigation menu on your web pages (in the live demo of this JavaScript code example, we have 3 levels; and obviously you can add as many levels a... 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
*/
.menu1 {
color:white;
background: #000;
font-family:arial, helvetica, sans-serif;
font-weight:bold;
font-size:12px;
}
.menu2 {
background: #ffff00;
color: blue;
font-family:arial, helvetica, sans-serif;
font-size:12px;
line-height: 19px;
}
</style>
Step 2: Copy & Paste JavaScript code 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
var exp = 5;
function newCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameSG = name + "=";
var nuller = '';
if (document.cookie.indexOf(nameSG) == -1)
return nuller;
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameSG) == 0) return c.substring(nameSG.length,c.length);
}
return null;
}
function eraseCookie(name) {
newCookie(name,"",-1);
}
if (document.getElementById) {
document.writeln('<style type="text/css">')
document.writeln('.main {text-decoration:none; color:blue; cursor:hand; cursor:pointer}')
document.writeln('span:hover.mainLink {text-decoration:underline; color:red}')
document.writeln('.sublinks1 {display:none; padding-left:14px}')
document.writeln('.link2 {text-decoration:none; color:blue}')
document.writeln('a:hover.link2 {text-decoration:underline; color:red}')
document.writeln('</style>') }
// Below you should add a1, a2 etc. for each main link you wish to include
// so if you want 3 main links you should add a1, a2, a3 in the format shown
// enclosed in double quotes
var mainNum = new Array("a1","a2","a3");
// Below you should add b1, b2 etc. for each sub link you wish to include
// under one main link, here the first main link. so if you want 4 sub links you
// should add b1, b2, b3, b4 in the format shown enclosed in double quotes
var subNum1 = new Array("b1","b2");
// Below, this is for sub links under the second main link. there are 3 sub links
// in the given example
var subNum2 = new Array("c1","c2","c3");
function openClose(theName, menuArray, theID) {
for(var i=0; i < menuArray.length; i++) {
if (menuArray[i] == theID) {
if (document.getElementById(theID).style.display == "block") {
document.getElementById(theID).style.display = "none";
document.getElementById("tick_"+menuArray[i]).innerHTML = "+";
eraseCookie(theName); }
else {
document.getElementById(theID).style.display = "block";
document.getElementById("tick_"+menuArray[i]).innerHTML = "-";
newCookie(theName,menuArray[i],exp); }
}
else {
document.getElementById(menuArray[i]).style.display = "none";
document.getElementById("tick_"+menuArray[i]).innerHTML = "+";
}
}
}
function memStatus() {
var num = readCookie("MN");
if (num) {
document.getElementById(num).style.display = "block";
document.getElementById("tick_"+num).innerHTML = "-"; }
var num1 = readCookie("SB");
if (num1) {
document.getElementById(num1).style.display = "block";
document.getElementById("tick_"+num1).innerHTML = "-"; }
}
// 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() {
memStatus();
});
</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
*/
-->
<table border="0" width="130" bgcolor="#ffffff" cellpadding="2" cellspacing="0" style="background:#ffff00; color:#000000; border:#000000 1px solid">
<tr>
<td class="menu1">Collapsible Menu with Memory</td></tr>
<tr>
<td class="menu2">
<div onClick="openClose('MN',mainNum,'a1')" class="main"><span id="tick_a1">+</span> <span class="mainLink">Computing Links</span></div>
<div id="a1" class="sublinks1">
<!-- below is an example of nested sub-links under the first main link. -->
<div onClick="openClose('SB',subNum1,'b1')" class="main"><span id="tick_b1">+</span> <span class="mainLink">More Links</span></div>
<div id="b1" class="sublinks1">
<a href="http://www.thedomain.com/" class="link2">Sub-Link 1</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 2</a><br />-------------<br />
</div>
<div onClick="openClose('SB',subNum1,'b2')" class="main"><span id="tick_b2">+</span> <span class="mainLink">Few More Links</span></div>
<div id="b2" class="sublinks1">
<a href="http://www.thedomain.com/" class="link2">Sub-Link 1</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 2</a><br />-------------<br />
</div>
<!-- end of nested sub-links example. -->
<a href="http://www.microsoft.com/" class="link2">Microsoft Corp.</a><br />
<a href="http://home.netscape.com/" class="link2">Netscape Corp.</a><br />
<a href="http://www.macromedia.com/" class="link2">Macromedia Inc.</a><br />
<a href="http://www.symantec.com/" class="link2">Symantec Corp.</a><br />------------------------<br />
</div>
<div onClick="openClose('MN',mainNum,'a2')" class="main"><span id="tick_a2">+</span> <span class="mainLink">JavaScript Links</span></div>
<div id="a2" class="sublinks1">
<!-- below is an example of nested sub-links under the second main link. -->
<div onClick="openClose('SB',subNum2,'c1')" class="main"><span id="tick_c1">+</span> <span class="mainLink">More Links</span></div>
<div id="c1" class="sublinks1">
<a href="http://www.thedomain.com/" class="link2">Sub-Link 1</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 2</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 3</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 4</a><br />-------------<br />
</div>
<div onClick="openClose('SB',subNum2,'c2')" class="main"><span id="tick_c2">+</span> <span class="mainLink">Few More Links</span></div>
<div id="c2" class="sublinks1">
<a href="http://www.thedomain.com/" class="link2">Sub-Link 1</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 2</a><br />-------------<br />
</div>
<div onClick="openClose('SB',subNum2,'c3')" class="main"><span id="tick_c3">+</span> <span class="mainLink">Even More Links</span></div>
<div id="c3" class="sublinks1">
<a href="http://www.thedomain.com/" class="link2">Sub-Link 1</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 2</a><br />
<a href="http://www.thedomain.com/" class="link2">Sub-Link 3</a><br />-------------<br />
</div>
<!-- end of nested sub-links example. -->
<a href="http://www.sivamdesign.com/scripts/" class="link">The JS Page</a><br />
<a href="http://javascriptbank.com/" class="link2">JavaScript Bank</a><br />
<a href="http://www.docjs.com/" class="link">Doc JavaScript</a><br />------------------------<br />
</div>
<div onClick="openClose('MN',mainNum,'a3')" class="main"><span id="tick_a3">+</span> <span class="mainLink">PHP Links</span></div>
<div id="a3" class="sublinks1">
<a href="http://php.resourceindex.com/Complete_Scripts/" class="link2">PHP Res. Index</a><br />
<a href="http://px.sklar.com/" class="link2">PHP Code Excng.</a><br />------------------------<br />
</div>
<div>
<a href="" class="link">Another Link 1</a><br />
<a href="" class="link">Another Link 2</a><br />
<a href="" class="link">Another Link 3</a><br />
</div>
</td></tr>
</table>
-
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: Use JavaScript code below to setup the script
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: Place HTML below in your BODY section
HTML
Code:
$ <input type="text" name="currencyField1" onchange="currency(this);" />
-
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: must download files below
Files
Awesome Tabbing Navigation with Prototype and AJAX.zip
-
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>
-
JsTetris: Free Awesome JavaScript Online Tetris Game
Perhaps Tetris is not weird with anyone because of its famousness, was born in 1984 (same age with Mario), Tetris is one of oldest games. And now, Tetris has been released over 125 millions copies, Te... 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">
/*
This script downloaded from www.JavaScriptBank.com
Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
html, body { height: 100%; margin: 0; padding: 0; }
body {
background: #E1D4C0;
}
body, table {
font: 11px tahoma;
color: #826C55;
text-align: center;
}
/*** tetris 168,308 ***/
#tetris {
position: relative;
width: 300px;
height: 310px;
border: 1px solid #BAA68E;
background: #ffffff;
margin: 0 auto;
}
/*** left ***/
#tetris .left {
background: #F5EDE3;
position: absolute;
width: 130px;
height: 100%;
left: 0px;
top: 0px;
}
#tetris .left h1 {
font-size: 11px;
text-align: center;
margin-top: 10px;
margin-bottom: 10px;
}
#tetris .left h1 a {
color: #3366CC;
text-decoration: none;
}
#tetris .left h1 a:hover {
color: #FF6600;
text-decoration: none;
}
/* menu */
#tetris .left .menu {
text-align: center;
}
#tetris .left input {
font: 10px tahoma;
color: #333333;
text-transform: uppercase;
background: #EAE0D1;
}
#tetris .left .menu input {
width: 90px;
}
/* keyboard */
#tetris .left .keyboard {
position: absolute;
top: 163px;
left: 32px;
width: 85px;
height: 55px;
overflow: visible;
display: none;
}
#tetris .left .keyboard input {
font: 11px tahoma;
width: 25px;
height: 25px;
padding-bottom: 2px;
text-transform: none;
}
* html #tetris .left .keyboard input {
padding-left: 1px;
}
#tetris .left .keyboard .up {
position: absolute;
left: 30px;
top: 0px;
width: 30px;
height: 30px;
}
#tetris .left .keyboard .up input {
font: 15px tahoma;
padding-top: 3px;
}
#tetris .left .keyboard .down {
position: absolute;
left: 30px;
top: 30px;
width: 30px;
height: 30px;
}
#tetris .left .keyboard .down input {
font: 14px tahoma;
}
#tetris .left .keyboard .left {
position: absolute;
left: 0px;
top: 30px;
width: 30px;
height: 30px;
}
#tetris .left .keyboard .right {
position: absolute;
left: 60px;
top: 30px;
width: 30px;
height: 30px;
}
/* game over */
#tetris-gameover {
position: absolute;
width: 100%;
top: 50%;
text-align: center;
font-weight: bold;
display: none;
}
/* next puzzle */
#tetris-nextpuzzle {
position: absolute;
top: 49%;
left: 35%;
background: #ffffff;
overflow: visible;
display: none;
}
/* stats */
#tetris .left .stats {
position: absolute;
left: 35px;
bottom: 10px;
}
#tetris .stats td { padding-bottom: 1px; }
#tetris .stats .level { text-align: right; padding-right: 10px; }
#tetris-stats-level { font-weight: bold; }
#tetris .stats .time { text-align: right; padding-right: 10px; }
#tetris-stats-time { font-weight: bold; }
#tetris .stats .apm { text-align: right; padding-right: 10px; }
#tetris-stats-apm { font-weight: bold; }
#tetris .stats .lines { text-align: right; padding-right: 10px; }
#tetris-stats-lines { font-weight: bold; }
#tetris .stats .score { text-align: right; padding-right: 10px; }
#tetris-stats-score { font-weight: bold; }
/*** area ***/
#tetris-area {
background: #FFFFFF;
position: absolute;
width: 168px;
height: 308px;
left: 131px;
top: 1px;
overflow: hidden;
}
#tetris .block0,
#tetris .block1,
#tetris .block2,
#tetris .block3,
#tetris .block4,
#tetris .block5,
#tetris .block6 {
position: absolute;
width: 13px;
height: 13px;
border: 0.5px solid #ffffff;
/* with margin 0.5px there were problems with offsetLeft and offsetTop */
}
#tetris .block0,
#tetris .block1 {
background: #6699FF;
}
#tetris .block2,
#tetris .block3 {
background: #FF6600;
}
#tetris .block4 {
background: #FFAC1C;
}
#tetris .block5 {
background: #BAA68E;
}
#tetris .block6 {
background: #FF0000;
}
/*** window ***/
#tetris .window {
background: #EFE8DE;
position: absolute;
width: 168px;
height: 308px;
left: 131px;
top: 1px;
z-index: 5;
display: none;
}
#tetris .window .top {
position: relative;
background: #EAE0D1;
color: #666666;
font: 10px tahoma;
letter-spacing: +1px;
height: 20px;
line-height: 20px;
vertical-align: middle;
border-bottom: 1px solid #ffffff;
text-indent: 10px;
}
#tetris .window .top .close {
position: absolute;
background: #EAE0D1;
font: 11px verdana;
font-weight: bold;
right: 0px;
top: 0px;
height: 20px;
line-height: 19px;
text-indent: 7px;
width: 21px;
border-left: 1px solid #ffffff;
cursor: pointer;
}
#tetris .window .top .close:hover {
background: #EFE8DE;
}
#tetris .window .content {
font: 10px tahoma;
margin: 10px;
}
#tetris .window .content table {
font: 10px tahoma;
}
</style>
Step 2: Place JavaScript below in your HEAD section
JavaScript
Code:
<script type="text/javascript">
// Created by: Cezary Tomczak | http://gosu.pl
// Licensed under: BSD
// This script downloaded from www.JavaScriptBank.com
/*
* PROJECT: JsTetris
* VERSION: 1.1.0
* LICENSE: BSD (revised)
* AUTHOR: (c) 2004 Cezary Tomczak
* LINK: http://gosu.pl/dhtml/JsTetris.html
*
* This script can be used freely as long as all
* copyright messages are intact.
*/
/**
* Tetris Game
* Initializes the buttons automatically, no additional actions required
*
* Score:
* 1) puzzle speed = 80+700/level
* 2) if puzzles created in current level >= 10+level*2 then increase level
* 3) after puzzle falling score is increased by 1000*level*linesRemoved
* 4) each down action increases score by 5+level
*
* API:
*
* public - method can be called outside of the object
* event - method is used as event, "this" refers to html object, "self" refers to javascript object
*
* class Tetris
* ------------
* public event void start()
* public event void reset()
* public event void gameOver()
* public event void up()
* public event void down()
* public event void left()
* public event void right()
* public event void space()
*
* class Window
* ------------
* event void activate()
* event void close()
* public bool isActive()
*
* class Keyboard
* --------------
* public void set(int key, function func)
* event void event(object e)
*
* class Stats
* -----------
* public void start()
* public void stop()
* public void reset()
* public event void incTime()
* public void setScore(int i)
* public void setLevel(int i)
* public void setLines(int i)
* public void setPuzzles(int i)
* public void setActions(int i)
* public int getScore()
* public int getLevel()
* public int getLines()
* public int getPuzzles()
* public int getActions()
*
* class Area
* ----------
* public Constructor(int unit, int x, int y, string id)
* public void destroy()
* public int removeFullLines()
* public bool isLineFull(int y)
* public void removeLine(int y)
* public mixed getBlock(int y, int x)
* public void addElement(htmlObject el)
*
* class Puzzle
* ------------
* public Constructor(object area)
* public void reset()
* public bool isRunning()
* public bool isStopped()
* public int getX()
* public int getY()
* public bool mayPlace()
* public void place()
* public void destroy()
* private array createEmptyPuzzle(int y, int x)
* event void fallDown()
* public event void forceMoveDown()
* public void stop()
* public bool mayRotate()
* public void rotate()
* public bool mayMoveDown()
* public void moveDown()
* public bool mayMoveLeft()
* public void moveLeft()
* public bool mayMoveRight()
* public void moveRight()
*
* class Highscores
* ----------------
* public Constructor(maxscores)
* public void load()
* public void save()
* public bool mayAdd(int score)
* public void add(string name, int score)
* public array getScores()
* public string toHtml()
* private void sort()
*
* class Cookie
* ------------
* public string get(string name)
* public void set(string name, string value, int seconds, string path, string domain, bool secure)
* public void del(string name)
*
* TODO:
* document.getElementById("tetris-nextpuzzle") cache ?
*
*/
function Tetris() {
var self = this;
this.stats = new Stats();
this.puzzle = null;
this.area = null;
this.unit = 20; // unit = x pixels
this.areaX = 20; // area width = x units
this.areaY = 20; // area height = y units
this.highscores = new Highscores(10);
/**
* @return void
* @access public event
*/
this.start = function() {
self.reset();
self.stats.start();
document.getElementById("tetris-nextpuzzle").style.display = "block";
self.area = new Area(self.unit, self.areaX, self.areaY, "tetris-area");
self.puzzle = new Puzzle(self, self.area);
if (self.puzzle.mayPlace()) {
self.puzzle.place();
} else {
self.gameOver();
}
}
/**
* @return void
* @access public event
*/
this.reset = function() {
if (self.puzzle) {
self.puzzle.destroy();
self.puzzle = null;
}
if (self.area) {
self.area.destroy();
self.area = null;
}
document.getElementById("tetris-gameover").style.display = "none";
document.getElementById("tetris-nextpuzzle").style.display = "none";
self.stats.reset();
}
/**
* End game.
* Stop stats, ...
* @return void
* @access public event
*/
this.gameOver = function() {
self.stats.stop();
self.puzzle.stop();
document.getElementById("tetris-nextpuzzle").style.display = "none";
document.getElementById("tetris-gameover").style.display = "block";
if (this.highscores.mayAdd(this.stats.getScore())) {
var name = prompt("Game Over !\nEnter your name:", "");
if (name && name.trim().length) {
this.highscores.add(name, this.stats.getScore());
}
}
}
/**
* @return void
* @access public event
*/
this.up = function() {
if (self.puzzle && self.puzzle.isRunning() && !self.puzzle.isStopped()) {
if (self.puzzle.mayRotate()) {
self.puzzle.rotate();
self.stats.setActions(self.stats.getActions() + 1);
}
}
}
/**
* @return void
* @access public event
*/
this.down = function() {
if (self.puzzle && self.puzzle.isRunning() && !self.puzzle.isStopped()) {
if (self.puzzle.mayMoveDown()) {
self.stats.setScore(self.stats.getScore() + 5 + self.stats.getLevel());
self.puzzle.moveDown();
self.stats.setActions(self.stats.getActions() + 1);
}
}
}
/**
* @return void
* @access public event
*/
this.left = function() {
if (self.puzzle && self.puzzle.isRunning() && !self.puzzle.isStopped()) {
if (self.puzzle.mayMoveLeft()) {
self.puzzle.moveLeft();
self.stats.setActions(self.stats.getActions() + 1);
}
}
}
/**
* @return void
* @access public event
*/
this.right = function() {
if (self.puzzle && self.puzzle.isRunning() && !self.puzzle.isStopped()) {
if (self.puzzle.mayMoveRight()) {
self.puzzle.moveRight();
self.stats.setActions(self.stats.getActions() + 1);
}
}
}
/**
* @return void
* @access public event
*/
this.space = function() {
if (self.puzzle && self.puzzle.isRunning() && !self.puzzle.isStopped()) {
self.puzzle.stop();
self.puzzle.forceMoveDown();
}
}
// windows
var helpwindow = new Window("tetris-help");
var highscores = new Window("tetris-highscores");
// game menu
document.getElementById("tetris-menu-start").onclick = function() { helpwindow.close(); highscores.close(); self.start(); this.blur(); }
document.getElementById("tetris-menu-reset").onclick = function() { helpwindow.close(); highscores.close(); self.reset(); this.blur(); }
// help
document.getElementById("tetris-menu-help").onclick = function() { highscores.close(); helpwindow.activate(); this.blur(); }
document.getElementById("tetris-help-close").onclick = helpwindow.close;
// highscores
document.getElementById("tetris-menu-highscores").onclick = function() {
helpwindow.close();
document.getElementById("tetris-highscores-content").innerHTML = self.highscores.toHtml();
highscores.activate();
this.blur();
}
document.getElementById("tetris-highscores-close").onclick = highscores.close;
// keyboard - buttons
document.getElementById("tetris-keyboard-up").onclick = function() { self.up(); this.blur(); }
document.getElementById("tetris-keyboard-down").onclick = function() { self.down(); this.blur(); }
document.getElementById("tetris-keyboard-left").onclick = function () { self.left(); this.blur(); }
document.getElementById("tetris-keyboard-right").onclick = function() { self.right(); this.blur(); }
// keyboard
var keyboard = new Keyboard();
keyboard.set(keyboard.n, this.start);
keyboard.set(keyboard.r, this.reset);
keyboard.set(keyboard.up, this.up);
keyboard.set(keyboard.down, this.down);
keyboard.set(keyboard.left, this.left);
keyboard.set(keyboard.right, this.right);
keyboard.set(keyboard.space, this.space);
document.onkeydown = keyboard.event;
/**
* Window replaces game area, for example help window
* @param string id
*/
function Window(id) {
this.id = id;
this.el = document.getElementById(this.id);
var self = this;
/**
* Activate or deactivate a window - update html
* @return void
* @access event
*/
this.activate = function() {
self.el.style.display = (self.el.style.display == "block" ? "none" : "block");
}
/**
* Close window - update html
* @return void
* @access event
*/
this.close = function() {
self.el.style.display = "none";
}
/**
* @return bool
* @access public
*/
this.isActive = function() {
return (self.el.style.display == "block");
}
}
/**
* Assigning functions to keyboard events
* When key is pressed, searching in a table if any function has been assigned to this key, execute the function.
*/
function Keyboard() {
this.up = 38;
this.down = 40;
this.left = 37;
this.right = 39;
this.n = 78;
this.r = 82;
this.space = 32;
this.f12 = 123;
this.escape = 27;
this.keys = [];
this.funcs = [];
var self = this;
/**
* @param int key
* @param function func
* @return void
* @access public
*/
this.set = function(key, func) {
this.keys.push(key);
this.funcs.push(func);
}
/**
* @param object e
* @return void
* @access event
*/
this.event = function(e) {
if (!e) { e = window.event; }
for (var i = 0; i < self.keys.length; i++) {
if (e.keyCode == self.keys[i]) {
self.funcs[i]();
}
}
}
}
/**
* Live game statistics
* Updating html
*/
function Stats() {
this.level;
this.time;
this.apm;
this.lines;
this.score;
this.puzzles; // number of puzzles created on current level
this.actions;
this.el = {
"level": document.getElementById("tetris-stats-level"),
"time": document.getElementById("tetris-stats-time"),
"apm": document.getElementById("tetris-stats-apm"),
"lines": document.getElementById("tetris-stats-lines"),
"score": document.getElementById("tetris-stats-score")
}
this.timerId = null;
var self = this;
/**
* Start counting statistics, reset stats, turn on the timer
* @return void
* @access public
*/
this.start = function() {
this.reset();
this.timerId = setInterval(this.incTime, 1000);
}
/**
* Stop counting statistics, turn off the timer
* @return void
* @access public
*/
this.stop = function() {
if (this.timerId) {
clearInterval(this.timerId);
}
}
/**
* Reset statistics - update html
* @return void
* @access public
*/
this.reset = function() {
this.stop();
this.level = 1;
this.time = 0;
this.apm = 0;
this.lines = 0;
this.score = 0;
this.puzzles = 0;
this.actions = 0;
this.el.level.innerHTML = this.level;
this.el.time.innerHTML = this.time;
this.el.apm.innerHTML = this.apm;
this.el.lines.innerHTML = this.lines;
this.el.score.innerHTML = this.score;
}
/**
* Increase time, update apm - update html
* This func is called by setInterval()
* @return void
* @access public event
*/
this.incTime = function() {
self.time++;
self.el.time.innerHTML = self.time;
self.apm = parseInt((self.actions / self.time) * 60);
self.el.apm.innerHTML = self.apm;
}
/**
* Set score - update html
* @param int i
* @return void
* @access public
*/
this.setScore = function(i) {
this.score = i;
this.el.score.innerHTML = this.score;
}
/**
* Set level - update html
* @param int i
* @return void
* @access public
*/
this.setLevel = function(i) {
this.level = i;
this.el.level.innerHTML = this.level;
}
/**
* Set lines - update html
* @param int i
* @return void
* @access public
*/
this.setLines = function(i) {
this.lines = i;
this.el.lines.innerHTML = this.lines;
}
/**
* Number of puzzles created on current level
* @param int i
* @return void
* @access public
*/
this.setPuzzles = function(i) {
this.puzzles = i;
}
/**
* @param int i
* @return void
* @access public
*/
this.setActions = function(i) {
this.actions = i;
}
/**
* @return int
* @access public
*/
this.getScore = function() {
return this.score;
}
/**
* @return int
* @access public
*/
this.getLevel = function() {
return this.level;
}
/**
* @return int
* @access public
*/
this.getLines = function() {
return this.lines;
}
/**
* Number of puzzles created on current level
* @return int
* @access public
*/
this.getPuzzles = function() {
return this.puzzles;
}
/**
* @return int
* @access public
*/
this.getActions = function() {
return this.actions;
}
}
/**
* Area consists of blocks (2 dimensional board).
* Block contains "0" (if empty) or Html Object.
* @param int x
* @param int y
* @param string id
*/
function Area(unit, x, y, id) {
this.unit = unit;
this.x = x;
this.y = y;
this.el = document.getElementById(id);
this.board = [];
// create 2-dimensional board
for (var y = 0; y < this.y; y++) {
this.board.push(new Array());
for (var x = 0; x < this.x; x++) {
this.board[y].push(0);
}
}
/**
* Removing html elements from area.
* @return void
* @access public
*/
this.destroy = function() {
for (var y = 0; y < this.board.length; y++) {
for (var x = 0; x < this.board[y].length; x++) {
if (this.board[y][x]) {
this.el.removeChild(this.board[y][x]);
this.board[y][x] = 0;
}
}
}
}
/**
* Searching for full lines.
* Must go from the bottom of area to the top.
* Returns the number of lines removed - needed for Stats.score.
* @see isLineFull() removeLine()
* @return void
* @access public
*/
this.removeFullLines = function() {
var lines = 0;
for (var y = this.y - 1; y > 0; y--) {
if (this.isLineFull(y)) {
this.removeLine(y);
lines++;
y++;
}
}
return lines;
}
/**
* @param int y
* @return bool
* @access public
*/
this.isLineFull = function(y) {
for (var x = 0; x < this.x; x++) {
if (!this.board[y][x]) { return false; }
}
return true;
}
/**
* Remove given line
* Remove html objects
* All lines that are above given line move down by 1 unit
* @param int y
* @return void
* @access public
*/
this.removeLine = function(y) {
for (var x = 0; x < this.x; x++) {
this.el.removeChild(this.board[y][x]);
this.board[y][x] = 0;
}
y--;
for (; y > 0; y--) {
for (var x = 0; x < this.x; x++) {
if (this.board[y][x]) {
var el = this.board[y][x];
el.style.top = el.offsetTop + this.unit + "px";
this.board[y+1][x] = el;
this.board[y][x] = 0;
}
}
}
}
/**
* @param int y
* @param int x
* @return mixed 0 or Html Object
* @access public
*/
this.getBlock = function(y, x) {
if (y < 0) { return 0; }
if (y < this.y && x < this.x) {
return this.board[y][x];
} else {
throw "Area.getBlock("+y+", "+x+") failed";
}
}
/**
* Add Html Element to the area.
* Find (x,y) position using offsetTop and offsetLeft
* @param object el
* @return void
* @access public
*/
this.addElement = function(el) {
var x = parseInt(el.offsetLeft / this.unit);
var y = parseInt(el.offsetTop / this.unit);
if (y >= 0 && y < this.y && x >= 0 && x < this.x) {
this.board[y][x] = el;
} else {
// not always an error ..
}
}
}
/**
* Puzzle consists of blocks.
* Each puzzle after rotating 4 times, returns to its primitive position.
*/
function Puzzle(tetris, area) {
var self = this;
this.tetris = tetris;
this.area = area;
// timeout ids
this.fallDownID = null;
this.forceMoveDownID = null;
this.type = null; // 0..6
this.nextType = null; // next puzzle
this.position = null; // 0..3
this.speed = null;
this.running = null;
this.stopped = null;
this.board = []; // filled with html elements after placing on area
this.elements = [];
this.nextElements = []; // next board elements
// (x,y) position of the puzzle (top-left)
this.x = null;
this.y = null;
// width & height must be the same
this.puzzles = [
[
[0,0,1],
[1,1,1],
[0,0,0]
],
[
[1,0,0],
[1,1,1],
[0,0,0]
],
[
[0,1,1],
[1,1,0],
[0,0,0]
],
[
[1,1,0],
[0,1,1],
[0,0,0]
],
[
[0,1,0],
[1,1,1],
[0,0,0]
],
[
[1,1],
[1,1]
],
[
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
[0,0,0,0]
]
];
/**
* Reset puzzle. It does not destroy html elements in this.board.
* @return void
* @access public
*/
this.reset = function() {
if (this.fallDownID) {
clearTimeout(this.fallDownID);
}
if (this.forceMoveDownID) {
clearTimeout(this.forceMoveDownID);
}
this.type = this.nextType;
this.nextType = random(this.puzzles.length);
this.position = 0;
this.speed = 80 + (700 / this.tetris.stats.getLevel());
this.running = false;
this.stopped = false;
this.board = [];
this.elements = [];
for (var i = 0; i < this.nextElements.length; i++) {
document.getElementById("tetris-nextpuzzle").removeChild(this.nextElements[i]);
}
this.nextElements = [];
this.x = null;
this.y = null;
}
this.nextType = random(this.puzzles.length);
this.reset();
/**
* Check whether puzzle is running.
* @return bool
* @access public
*/
this.isRunning = function() {
return this.running;
}
/**
* Check whether puzzle has been stopped by user. It happens when user clicks
* "down" when puzzle is already at the bottom of area. The puzzle may still
* be running with event fallDown(). When puzzle is stopped, no actions will be
* performed when user press a key.
* @return bool
* @access public
*/
this.isStopped = function() {
return this.stopped;
}
/**
* Get X position of puzzle (top-left)
* @return int
* @access public
*/
this.getX = function() {
return this.x;
}
/**
* Get Y position of puzzle (top-left)
* @return int
* @access public
*/
this.getY = function() {
return this.y;
}
/**
* Check whether new puzzle may be placed on the area.
* Find (x,y) in area where beginning of the puzzle will be placed.
* Check if first puzzle line (checking from the bottom) can be placed on the area.
* @return bool
* @access public
*/
this.mayPlace = function() {
var puzzle = this.puzzles[this.type];
var areaStartX = parseInt((this.area.x - puzzle[0].length) / 2);
var areaStartY = 1;
var lineFound = false;
var lines = 0;
for (var y = puzzle.length - 1; y >= 0; y--) {
for (var x = 0; x < puzzle[y].length; x++) {
if (puzzle[y][x]) {
lineFound = true;
if (this.area.getBlock(areaStartY, areaStartX + x)) { return false; }
}
}
if (lineFound) {
lines++;
}
if (areaStartY - lines < 0) {
break;
}
}
return true;
}
/**
* Create empty board, create blocks in area - html objects, update puzzle board.
* Check puzzles on current level, increase level if needed.
* @return void
* @access public
*/
this.place = function() {
// stats
this.tetris.stats.setPuzzles(this.tetris.stats.getPuzzles() + 1);
if (this.tetris.stats.getPuzzles() >= (10 + this.tetris.stats.getLevel() * 2)) {
this.tetris.stats.setLevel(this.tetris.stats.getLevel() + 1);
this.tetris.stats.setPuzzles(0);
}
// init
var puzzle = this.puzzles[this.type];
var areaStartX = parseInt((this.area.x - puzzle[0].length) / 2);
var areaStartY = 1;
var lineFound = false;
var lines = 0;
this.x = areaStartX;
this.y = 1;
this.board = this.createEmptyPuzzle(puzzle.length, puzzle[0].length);
// create puzzle
for (var y = puzzle.length - 1; y >= 0; y--) {
for (var x = 0; x < puzzle[y].length; x++) {
if (puzzle[y][x]) {
lineFound = true;
var el = document.createElement("div");
el.className = "block" + this.type;
el.style.left = (areaStartX + x) * this.area.unit + "px";
el.style.top = (areaStartY - lines) * this.area.unit + "px";
this.area.el.appendChild(el);
this.board[y][x] = el;
this.elements.push(el);
}
}
if (lines) {
this.y--;
}
if (lineFound) {
lines++;
}
}
this.running = true;
this.fallDownID = setTimeout(this.fallDown, this.speed);
// next puzzle
var nextPuzzle = this.puzzles[this.nextType];
for (var y = 0; y < nextPuzzle.length; y++) {
for (var x = 0; x < nextPuzzle[y].length; x++) {
if (nextPuzzle[y][x]) {
var el = document.createElement("div");
el.className = "block" + this.nextType;
el.style.left = (x * this.area.unit) + "px";
el.style.top = (y * this.area.unit) + "px";
document.getElementById("tetris-nextpuzzle").appendChild(el);
this.nextElements.push(el);
}
}
}
}
/**
* Remove puzzle from the area.
* Clean some other stuff, see reset()
* @return void
* @access public
*/
this.destroy = function() {
for (var i = 0; i < this.elements.length; i++) {
this.area.el.removeChild(this.elements[i]);
}
this.elements = [];
this.board = [];
this.reset();
}
/**
* @param int y
* @param int x
* @return array
* @access private
*/
this.createEmptyPuzzle = function(y, x) {
var puzzle = [];
for (var y2 = 0; y2 < y; y2++) {
puzzle.push(new Array());
for (var x2 = 0; x2 < x; x2++) {
puzzle[y2].push(0);
}
}
return puzzle;
}
/**
* Puzzle fall from the top to the bottom.
* After placing a puzzle, this event will be called as long as the puzzle is running.
* @see place() stop()
* @return void
* @access event
*/
this.fallDown = function() {
if (self.isRunning()) {
if (self.mayMoveDown()) {
self.moveDown();
self.fallDownID = setTimeout(self.fallDown, self.speed);
} else {
// move blocks into area board
for (var i = 0; i < self.elements.length; i++) {
self.area.addElement(self.elements[i]);
}
// stats
var lines = self.area.removeFullLines();
if (lines) {
self.tetris.stats.setLines(self.tetris.stats.getLines() + lines);
self.tetris.stats.setScore(self.tetris.stats.getScore() + (1000 * self.tetris.stats.getLevel() * lines));
}
// reset puzzle
self.reset();
if (self.mayPlace()) {
self.place();
} else {
self.tetris.gameOver();
}
}
}
}
/**
* After clicking "space" the puzzle is forced to move down, no user action is performed after
* this event is called. this.running must be set to false. This func is similiar to fallDown()
* Also update score & actions - like Tetris.down()
* @see fallDown()
* @return void
* @access public event
*/
this.forceMoveDown = function() {
if (!self.isRunning() && !self.isStopped()) {
if (self.mayMoveDown()) {
// stats: score, actions
self.tetris.stats.setScore(self.tetris.stats.getScore() + 5 + self.tetris.stats.getLevel());
self.tetris.stats.setActions(self.tetris.stats.getActions() + 1);
self.moveDown();
self.forceMoveDownID = setTimeout(self.forceMoveDown, 30);
} else {
// move blocks into area board
for (var i = 0; i < self.elements.length; i++) {
self.area.addElement(self.elements[i]);
}
// stats: lines
var lines = self.area.removeFullLines();
if (lines) {
self.tetris.stats.setLines(self.tetris.stats.getLines() + lines);
self.tetris.stats.setScore(self.tetris.stats.getScore() + (1000 * self.tetris.stats.getLevel() * lines));
}
// reset puzzle
self.reset();
if (self.mayPlace()) {
self.place();
} else {
self.tetris.gameOver();
}
}
}
}
/**
* Stop the puzzle falling
* @return void
* @access public
*/
this.stop = function() {
this.running = false;
}
/**
* Check whether puzzle may be rotated.
* Check down, left, right, rotate
* @return bool
* @access public
*/
this.mayRotate = function() {
for (var y = 0; y < this.board.length; y++) {
for (var x = 0; x < this.board[y].length; x++) {
if (this.board[y][x]) {
var newY = this.getY() + this.board.length - 1 - x;
var newX = this.getX() + y;
if (newY >= this.area.y) { return false; }
if (newX < 0) { return false; }
if (newX >= this.area.x) { return false; }
if (this.area.getBlock(newY, newX)) { return false; }
}
}
}
return true;
}
/**
* Rotate the puzzle to the left.
* @return void
* @access public
*/
this.rotate = function() {
var puzzle = this.createEmptyPuzzle(this.board.length, this.board[0].length);
for (var y = 0; y < this.board.length; y++) {
for (var x = 0; x < this.board[y].length; x++) {
if (this.board[y][x]) {
var newY = puzzle.length - 1 - x;
var newX = y;
var el = this.board[y][x];
var moveY = newY - y;
var moveX = newX - x;
el.style.left = el.offsetLeft + (moveX * this.area.unit) + "px";
el.style.top = el.offsetTop + (moveY * this.area.unit) + "px";
puzzle[newY][newX] = el;
}
}
}
this.board = puzzle;
}
/**
* Check whether puzzle may be moved down.
* - is any other puzzle on the way ?
* - is it end of the area ?
* If false, then true is assigned to variable this.stopped - no user actions will be performed to this puzzle,
* so this func should be used carefully, only in Tetris.down() and Tetris.puzzle.fallDown()
* @return bool
* @access public
*/
this.mayMoveDown = function() {
for (var y = 0; y < this.board.length; y++) {
for (var x = 0; x < this.board[y].length; x++) {
if (this.board[y][x]) {
if (this.getY() + y + 1 >= this.area.y) { this.stopped = true; return false; }
if (this.area.getBlock(this.getY() + y + 1, this.getX() + x)) { this.stopped = true; return false; }
}
}
}
return true;
}
/**
* Move the puzzle down by 1 unit.
* @return void
* @access public
*/
this.moveDown = function() {
for (var i = 0; i < this.elements.length; i++) {
this.elements[i].style.top = this.elements[i].offsetTop + this.area.unit + "px";
}
this.y++;
}
/**
* Check whether puzzle may be moved left.
* - is any other puzzle on the way ?
* - is the end of the area
* @return bool
* @access public
*/
this.mayMoveLeft = function() {
for (var y = 0; y < this.board.length; y++) {
for (var x = 0; x < this.board[y].length; x++) {
if (this.board[y][x]) {
if (this.getX() + x - 1 < 0) { return false; }
if (this.area.getBlock(this.getY() + y, this.getX() + x - 1)) { return false; }
}
}
}
return true;
}
/**
* Move the puzzle left by 1 unit
* @return void
* @access public
*/
this.moveLeft = function() {
for (var i = 0; i < this.elements.length; i++) {
this.elements[i].style.left = this.elements[i].offsetLeft - this.area.unit + "px";
}
this.x--;
}
/**
* Check whether puzle may be moved right.
* - is any other puzzle on the way ?
* - is the end of the area
* @return bool
* @access public
*/
this.mayMoveRight = function() {
for (var y = 0; y < this.board.length; y++) {
for (var x = 0; x < this.board[y].length; x++) {
if (this.board[y][x]) {
if (this.getX() + x + 1 >= this.area.x) { return false; }
if (this.area.getBlock(this.getY() + y, this.getX() + x + 1)) { return false; }
}
}
}
return true;
}
/**
* Move the puzzle right by 1 unit.
* @return void
* @access public
*/
this.moveRight = function() {
for (var i = 0; i < this.elements.length; i++) {
this.elements[i].style.left = this.elements[i].offsetLeft + this.area.unit + "px";
}
this.x++;
}
}
/**
* Generates random number that is >= 0 and < i
* @return int
* @access private
*/
function random(i) {
return Math.floor(Math.random() * i);
}
/**
* Store highscores in cookie.
*/
function Highscores(maxscores) {
this.maxscores = maxscores;
this.scores = [];
/**
* Load scores from cookie.
* Note: it is automatically called when creating new instance of object Highscores.
* @return void
* @access public
*/
this.load = function() {
var cookie = new Cookie();
var s = cookie.get("tetris-highscores");
this.scores = [];
if (s.length) {
var scores = s.split("|");
for (var i = 0; i < scores.length; ++i) {
var a = scores[i].split(":");
this.scores.push(new Score(a[0], Number(a[1])));
}
}
}
/**
* Save scores to cookie.
* Note: it is automatically called after adding new score.
* @return void
* @access public
*/
this.save = function() {
var cookie = new Cookie();
var a = [];
for (var i = 0; i < this.scores.length; ++i) {
a.push(this.scores[i].name+":"+this.scores[i].score);
}
var s = a.join("|");
cookie.set("tetris-highscores", s, 3600*24*1000);
}
/**
* Is the score high enough to be able to add ?
* @return bool
* @access public
*/
this.mayAdd = function(score) {
if (this.scores.length < this.maxscores) { return true; }
for (var i = this.scores.length - 1; i >= 0; --i) {
if (this.scores[i].score < score) { return true; }
}
return false;
}
/**
* @param string name
* @param int score
* @return void
* @access public
*/
this.add = function(name, score) {
name = name.replace(/[;=:|]/g, "?");
name = name.replace(/</g, "<").replace(/>/g, ">");
if (this.scores.length < this.maxscores) {
this.scores.push(new Score(name, score));
} else {
for (var i = this.scores.length - 1; i >= 0; --i) {
if (this.scores[i].score < score) {
this.scores.removeByIndex(i);
this.scores.push(new Score(name, score));
break;
}
}
}
this.sort();
this.save();
}
/**
* Get array of scores.
* @return array [Score, Score, ..]
* @access public
*/
this.getScores = function() {
return this.scores;
}
/**
* All highscores returned in html friendly format.
* @return string
* @access public
*/
this.toHtml = function() {
var s = '<table cellspacing="0" cellpadding="2"><tr><th></th><th>Name</th><th>Score</th></tr>';
for (var i = 0; i < this.scores.length; ++i) {
s += '<tr><td>?.</td><td>?</td><td>?</td></tr>'.format(i+1, this.scores[i].name, this.scores[i].score);
}
s += '</table>';
return s;
}
/**
* Sort table with scores.
* @return void
* @access private
*/
this.sort = function() {
var scores = this.scores;
var len = scores.length;
this.scores = [];
for (var i = 0; i < len; ++i) {
var el = null, index = null;
for (var j = 0; j < scores.length; ++j) {
if (!el || (scores[j].score > el.score)) {
el = scores[j];
index = j;
}
}
scores.removeByIndex(index);
this.scores.push(el);
}
}
/* Simple score object. */
function Score(name, score) {
this.name = name;
this.score = score;
}
this.load();
}
/**
* Managing cookies.
*/
function Cookie() {
/**
* @param string name
* @return string
* @access public
*/
this.get = function(name) {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; ++i) {
var a = cookies[i].split("=");
if (a.length == 2) {
a[0] = a[0].trim();
a[1] = a[1].trim();
if (a[0] == name) {
return unescape(a[1]);
}
}
}
return "";
};
/**
* @param string name
* @param string value (do not use special chars like ";" "=")
* @param int seconds
* @param string path
* @param string domain
* @param bool secure
* @return void
* @access public
*/
this.set = function(name, value, seconds, path, domain, secure) {
var cookie = (name + "=" + escape(value));
if (seconds) {
var date = new Date(new Date().getTime()+seconds*1000);
cookie += ("; expires="+date.toGMTString());
}
cookie += (path ? "; path="+path : "");
cookie += (domain ? "; domain="+domain : "");
cookie += (secure ? "; secure" : "");
document.cookie = cookie;
};
/**
* @param name
* @return void
* @access public
*/
this.del = function(name) {
document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
};
}
}
if (!String.prototype.trim) {
String.prototype.trim = function() {
return this.replace(/^\s*|\s*$/g, "");
};
}
if (!Array.prototype.removeByIndex) {
Array.prototype.removeByIndex = function(index) {
this.splice(index, 1);
};
}
if (!String.prototype.format) {
String.prototype.format = function() {
if (!arguments.length) { throw "String.format() failed, no arguments passed, this = "+this; }
var tokens = this.split("?");
if (arguments.length != (tokens.length - 1)) { throw "String.format() failed, tokens != arguments, this = "+this; }
var s = tokens[0];
for (var i = 0; i < arguments.length; ++i) {
s += (arguments[i] + tokens[i + 1]);
}
return s;
};
}
</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
*/
-->
<table cellspacing="0" cellpadding="0" width="100%" height="100%"><tr><td valign="middle">
<div id="tetris">
<div class="left">
<h1>JsTetris 1.1.0</h1>
<div class="menu">
<div><input type="button" value="New Game" id="tetris-menu-start" /></div>
<div><input type="button" value="Reset" id="tetris-menu-reset" /></div>
<div><input type="button" value="Help" id="tetris-menu-help" /></div>
<div><input type="button" value="Highscores" id="tetris-menu-highscores" /></div>
</div>
<div class="keyboard">
<div class="up"><input type="button" value="^" id="tetris-keyboard-up" /></div>
<div class="down"><input type="button" value="v" id="tetris-keyboard-down" /></div>
<div class="left"><input type="button" value="<" id="tetris-keyboard-left" /></div>
<div class="right"><input type="button" value=">" id="tetris-keyboard-right" /></div>
</div>
<div id="tetris-nextpuzzle"></div>
<div id="tetris-gameover">Game Over</div>
<div class="stats">
<table cellspacing="0" cellpadding="0">
<tr>
<td class="level">Level:</td>
<td><span id="tetris-stats-level">1</span></td>
</tr>
<tr>
<td class="score">Score:</td>
<td><span id="tetris-stats-score">0</span></td>
</tr>
<tr>
<td class="lines">Lines:</td>
<td><span id="tetris-stats-lines">0</span></td>
</tr>
<tr>
<td class="apm">APM:</td>
<td><span id="tetris-stats-apm">0</span></td>
</tr>
<tr>
<td class="time">Time:</td>
<td><span id="tetris-stats-time">0</span></td>
</tr>
</table>
</div>
</div>
<div id="tetris-area"></div>
<div id="tetris-help" class="window">
<div class="top">
Help <span id="tetris-help-close" class="close">x</span>
</div>
<div class="content">
<b>Controllers:</b> <br />
up - rotate <br />
down - move down <br />
left - move left <br />
right - move right <br />
space - fall to the bottom <br />
n - new game <br />
r - reset <br />
<br />
<b>Rules:</b> <br />
1) Puzzle speed = 80+700/level miliseconds, the smaller value the faster puzzle falls <br />
2) If puzzles created in current level >= 10+level*2 then increase level <br />
3) After puzzle falling score is increased by 1000*level*linesRemoved <br />
4) Each "down" action increases score by 5+level (pressing space counts as multiple down actions)
</div>
</div>
<div id="tetris-highscores" class="window">
<div class="top">
Highscores <span id="tetris-highscores-close" class="close">x</span>
</div>
<div class="content">
<div id="tetris-highscores-content"></div>
<br />
Note: these scores are kept in cookies, they are only visible to your computer, other players that visit this page see their own scores.
</div>
</div>
</div>
</td></tr></table>
<script type="text/javascript">
var tetris = new Tetris();
tetris.unit = 14;
tetris.areaX = 12;
tetris.areaY = 22;
</script>
-
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: Use CSS code below for styling the script
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: Place JavaScript 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: 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 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>
-
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: must download files below
Files
Cool Analog Clock with Raphael by Amazing Styles.zip
-
Simple Programming Language Code Syntax Highlighter with JavaScript
Highlighting the source codes is one very great and important functions for the website/blog that mainly shows source codes on the web pages, jsB@nk also presented you many source code 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
*/
/* Pretty printing styles. */
.str { color: #080; }
.kwd { color: #008; }
.com { color: #800; }
.typ { color: #606; }
.lit { color: #066; }
.pun { color: #660; }
.pln { color: #000; }
.tag { color: #008; }
.atn { color: #606; }
.atv { color: #080; }
.dec { color: #606; }
pre.prettyprint { padding: 10px; border: 1px solid #888; text-align: left;}
@media print {
.str { color: #060; }
.kwd { color: #006; font-weight: bold; }
.com { color: #600; font-style: italic; }
.typ { color: #404; font-weight: bold; }
.lit { color: #044; }
.pun { color: #440; }
.pln { color: #000; }
.tag { color: #006; font-weight: bold; }
.atn { color: #404; }
.atv { color: #060; }
}
</style>
Step 2: Place JavaScript below in your HEAD section
JavaScript
Code:
<script type="text/javascript">
// Created by: Mike Samuel | http://code.google.com/p/google-code-prettify/
// This script downloaded from www.JavaScriptBank.com
/* Copyright (C) 2006 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Use these codes to determine the display colors:
id="bash"
id="C"
id="Cpp"
id="java"
id="issue12"
id="python"
id="xml"
id="htmlXmp"
id="xhtml"
id="PHP"
id="xsl"
id="whitespace"
Example:
<pre class="prettyprint" id="javascript">
... code ...
</pre>
<code class="prettyprint" id="javascript">... code ...</code>
*/
// ===========================================================
var PR_keywords = {};
/** initialize the keyword list for our target languages. */
(function () {
var CPP_KEYWORDS = "abstract bool break case catch char class const " +
"const_cast continue default delete deprecated dllexport dllimport do " +
"double dynamic_cast else enum explicit extern false float for friend " +
"goto if inline int long mutable naked namespace new noinline noreturn " +
"nothrow novtable operator private property protected public register " +
"reinterpret_cast return selectany short signed sizeof static " +
"static_cast struct switch template this thread throw true try typedef " +
"typeid typename union unsigned using declaration, directive uuid " +
"virtual void volatile while typeof";
var CSHARP_KEYWORDS = "as base by byte checked decimal delegate descending " +
"event finally fixed foreach from group implicit in interface internal " +
"into is lock null object out override orderby params readonly ref sbyte " +
"sealed stackalloc string select uint ulong unchecked unsafe ushort var";
var JAVA_KEYWORDS = "package synchronized boolean implements import throws " +
"instanceof transient extends final strictfp native super";
var JSCRIPT_KEYWORDS = "debugger export function with NaN Infinity";
var PERL_KEYWORDS = "require sub unless until use elsif BEGIN END";
var PYTHON_KEYWORDS = "and assert def del elif except exec global lambda " +
"not or pass print raise yield False True None";
var RUBY_KEYWORDS = "then end begin rescue ensure module when undef next " +
"redo retry alias defined";
var SH_KEYWORDS = "done fi";
var KEYWORDS = [CPP_KEYWORDS, CSHARP_KEYWORDS, JAVA_KEYWORDS,
JSCRIPT_KEYWORDS, PERL_KEYWORDS, PYTHON_KEYWORDS,
RUBY_KEYWORDS, SH_KEYWORDS];
for (var k = 0; k < KEYWORDS.length; k++) {
var kw = KEYWORDS[k].split(' ');
for (var i = 0; i < kw.length; i++) {
if (kw[i]) { PR_keywords[kw[i]] = true; }
}
}
}).call(this);
// token style names. correspond to css classes
/** token style for a string literal */
var PR_STRING = 'str';
/** token style for a keyword */
var PR_KEYWORD = 'kwd';
/** token style for a comment */
var PR_COMMENT = 'com';
/** token style for a type */
var PR_TYPE = 'typ';
/** token style for a literal value. e.g. 1, null, true. */
var PR_LITERAL = 'lit';
/** token style for a punctuation string. */
var PR_PUNCTUATION = 'pun';
/** token style for a punctuation string. */
var PR_PLAIN = 'pln';
/** token style for an sgml tag. */
var PR_TAG = 'tag';
/** token style for a markup declaration such as a DOCTYPE. */
var PR_DECLARATION = 'dec';
/** token style for embedded source. */
var PR_SOURCE = 'src';
/** token style for an sgml attribute name. */
var PR_ATTRIB_NAME = 'atn';
/** token style for an sgml attribute value. */
var PR_ATTRIB_VALUE = 'atv';
/** the number of characters between tab columns */
var PR_TAB_WIDTH = 8;
// some string utilities
function PR_isWordChar(ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
/** Splice one array into another.
* Like the python <code>
* container[containerPosition:containerPosition + countReplaced] = inserted
* </code>
* @param {Array} inserted
* @param {Array} container modified in place
* @param {Number} containerPosition
* @param {Number} countReplaced
*/
function PR_spliceArrayInto(
inserted, container, containerPosition, countReplaced) {
inserted.unshift(containerPosition, countReplaced || 0);
try {
container.splice.apply(container, inserted);
} finally {
inserted.splice(0, 2);
}
}
/** a set of tokens that can precede a regular expression literal in javascript.
* http://www.mozilla.org/js/language/js20/rationale/syntax.html has the full
* list, but I've removed ones that might be problematic when seen in languages
* that don't support regular expression literals.
*
* <p>Specifically, I've removed any keywords that can't precede a regexp
* literal in a syntactically legal javascript program, and I've removed the
* "in" keyword since it's not a keyword in many languages, and might be used
* as a count of inches.
* @private
*/
var REGEXP_PRECEDER_PATTERN = (function () {
var preceders = [
"!", "!=", "!==", "#", "%", "%=", "&", "&&", "&&=",
"&=", "(", "*", "*=", /* "+", */ "+=", ",", /* "-", */ "-=",
"->", /*".", "..", "...", handled below */ "/", "/=", ":", "::", ";",
"<", "<<", "<<=", "<=", "=", "==", "===", ">",
">=", ">>", ">>=", ">>>", ">>>=", "?", "@", "[",
"^", "^=", "^^", "^^=", "{", "|", "|=", "||",
"||=", "~", "break", "case", "continue", "delete",
"do", "else", "finally", "instanceof",
"return", "throw", "try", "typeof"
];
var pattern = '(?:' +
'(?:(?:^|[^0-9\.])\\.{1,3})|' + // a dot that's not part of a number
'(?:(?:^|[^\\+])\\+)|' + // allow + but not ++
'(?:(?:^|[^\\-])-)' // allow - but not --
;
for (var i = 0; i < preceders.length; ++i) {
var preceder = preceders[i];
if (PR_isWordChar(preceder.charAt(0))) {
pattern += '|\\b' + preceder;
} else {
pattern += '|' + preceder.replace(/([^=<>:&])/g, '\\$1');
}
}
pattern += '|^)\\s*$'; // matches at end, and matches empty string
return new RegExp(pattern);
// CAVEAT: this does not properly handle the case where a regular expression
// immediately follows another since a regular expression may have flags
// for case-sensitivity and the like. Having regexp tokens adjacent is not
// valid in any language I'm aware of, so I'm punting.
// TODO: maybe style special characters inside a regexp as punctuation.
})();
// Define regexps here so that the interpreter doesn't have to create an object
// each time the function containing them is called.
// The language spec requires a new object created even if you don't access the
// $1 members.
var pr_amp = /&/g;
var pr_lt = /</g;
var pr_gt = />/g;
var pr_quot = /\"/g;
/** like textToHtml but escapes double quotes to be attribute safe. */
function PR_attribToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>')
.replace(pr_quot, '"');
}
/** escapest html special characters to html. */
function PR_textToHtml(str) {
return str.replace(pr_amp, '&')
.replace(pr_lt, '<')
.replace(pr_gt, '>');
}
var pr_ltEnt = /</g;
var pr_gtEnt = />/g;
var pr_aposEnt = /'/g;
var pr_quotEnt = /"/g;
var pr_ampEnt = /&/g;
/** unescapes html to plain text. */
function PR_htmlToText(html) {
var pos = html.indexOf('&');
if (pos < 0) { return html; }
// Handle numeric entities specially. We can't use functional substitution
// since that doesn't work in older versions of Safari.
// These should be rare since most browsers convert them to normal chars.
for (--pos; (pos = html.indexOf('&#', pos + 1)) >= 0;) {
var end = html.indexOf(';', pos);
if (end >= 0) {
var num = html.substring(pos + 3, end);
var radix = 10;
if (num && num.charAt(0) == 'x') {
num = num.substring(1);
radix = 16;
}
var codePoint = parseInt(num, radix);
if (!isNaN(codePoint)) {
html = (html.substring(0, pos) + String.fromCharCode(codePoint) +
html.substring(end + 1));
}
}
}
return html.replace(pr_ltEnt, '<')
.replace(pr_gtEnt, '>')
.replace(pr_aposEnt, "'")
.replace(pr_quotEnt, '"')
.replace(pr_ampEnt, '&');
}
/** is the given node's innerHTML normally unescaped? */
function PR_isRawContent(node) {
return 'XMP' == node.tagName;
}
var PR_innerHtmlWorks = null;
function PR_getInnerHtml(node) {
// inner html is hopelessly broken in Safari 2.0.4 when the content is
// an html description of well formed XML and the containing tag is a PRE
// tag, so we detect that case and emulate innerHTML.
if (null === PR_innerHtmlWorks) {
var testNode = document.createElement('PRE');
testNode.appendChild(
document.createTextNode('<!DOCTYPE foo PUBLIC "foo bar">\n<foo />'));
PR_innerHtmlWorks = !/</.test(testNode.innerHTML);
}
if (PR_innerHtmlWorks) {
var content = node.innerHTML;
// XMP tags contain unescaped entities so require special handling.
if (PR_isRawContent(node)) {
content = PR_textToHtml(content);
}
return content;
}
var out = [];
for (var child = node.firstChild; child; child = child.nextSibling) {
PR_normalizedHtml(child, out);
}
return out.join('');
}
/** walks the DOM returning a properly escaped version of innerHTML.
*/
function PR_normalizedHtml(node, out) {
switch (node.nodeType) {
case 1: // an element
var name = node.tagName.toLowerCase();
out.push('\074', name);
for (var i = 0; i < node.attributes.length; ++i) {
var attr = node.attributes[i];
if (!attr.specified) { continue; }
out.push(' ');
PR_normalizedHtml(attr, out);
}
out.push('>');
for (var child = node.firstChild; child; child = child.nextSibling) {
PR_normalizedHtml(child, out);
}
if (node.firstChild || !/^(?:br|link|img)$/.test(name)) {
out.push('<\/', name, '>');
}
break;
case 2: // an attribute
out.push(node.name.toLowerCase(), '="', PR_attribToHtml(node.value), '"');
break;
case 3: case 4: // text
out.push(PR_textToHtml(node.nodeValue));
break;
}
}
/** returns a function that expand tabs to spaces. This function can be fed
* successive chunks of text, and will maintain its own internal state to
* keep track of how tabs are expanded.
* @return {function (plainText : String) : String } a function that takes
* plain text and return the text with tabs expanded.
* @private
*/
function PR_tabExpander(tabWidth) {
var SPACES = ' ';
var charInLine = 0;
return function (plainText) {
// walk over each character looking for tabs and newlines.
// On tabs, expand them. On newlines, reset charInLine.
// Otherwise increment charInLine
var out = null;
var pos = 0;
for (var i = 0, n = plainText.length; i < n; ++i) {
var ch = plainText.charAt(i);
switch (ch) {
case '\t':
if (!out) { out = []; }
out.push(plainText.substring(pos, i));
// calculate how much space we need in front of this part
// nSpaces is the amount of padding -- the number of spaces needed to
// move us to the next column, where columns occur at factors of
// tabWidth.
var nSpaces = tabWidth - (charInLine % tabWidth);
charInLine += nSpaces;
for (; nSpaces >= 0; nSpaces -= SPACES.length) {
out.push(SPACES.substring(0, nSpaces));
}
pos = i + 1;
break;
case '\n':
charInLine = 0;
break;
default:
++charInLine;
}
}
if (!out) { return plainText; }
out.push(plainText.substring(pos));
return out.join('');
};
}
// The below pattern matches one of the following
// (1) /[^<]+/ : A run of characters other than '<'
// (2) /<!--.*?-->/: an HTML comment
// (3) /<!\[CDATA\[.*?\]\]>/: a cdata section
// (3) /<\/?[a-zA-Z][^>]*>/ : A probably tag that should not be highlighted
// (4) /</ : A '<' that does not begin a larger chunk. Treated as 1
var pr_chunkPattern =
/(?:[^<]+|<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\/?[a-zA-Z][^>]*>|<)/g;
var pr_commentPrefix = /^<!--/;
var pr_cdataPrefix = /^<\[CDATA\[/;
var pr_brPrefix = /^<br\b/i;
/** split markup into chunks of html tags (style null) and
* plain text (style {@link #PR_PLAIN}), converting tags which are significant
* for tokenization (<br>) into their textual equivalent.
*
* @param {String} s html where whitespace is considered significant.
* @return {Object} source code and extracted tags.
* @private
*/
function PR_extractTags(s) {
// since the pattern has the 'g' modifier and defines no capturing groups,
// this will return a list of all chunks which we then classify and wrap as
// PR_Tokens
var matches = s.match(pr_chunkPattern);
var sourceBuf = [];
var sourceBufLen = 0;
var extractedTags = [];
if (matches) {
for (var i = 0, n = matches.length; i < n; ++i) {
var match = matches[i];
if (match.length > 1 && match.charAt(0) === '<') {
if (pr_commentPrefix.test(match)) { continue; }
if (pr_cdataPrefix.test(match)) {
// strip CDATA prefix and suffix. Don't unescape since it's CDATA
sourceBuf.push(match.substring(9, match.length - 3));
sourceBufLen += match.length - 12;
} else if (pr_brPrefix.test(match)) {
// <br> tags are lexically significant so convert them to text.
// This is undone later.
// <br> tags are lexically significant
sourceBuf.push('\n');
sourceBufLen += 1;
} else {
extractedTags.push(sourceBufLen, match);
}
} else {
var literalText = PR_htmlToText(match);
sourceBuf.push(literalText);
sourceBufLen += literalText.length;
}
}
}
return { source: sourceBuf.join(''), tags: extractedTags };
}
/** Given triples of [style, pattern, context] returns a lexing function,
* The lexing function interprets the patterns to find token boundaries and
* returns a decoration list of the form
* [index_0, style_0, index_1, style_1, ..., index_n, style_n]
* where index_n is an index into the sourceCode, and style_n is a style
* constant like PR_PLAIN. index_n-1 <= index_n, and style_n-1 applies to
* all characters in sourceCode[index_n-1:index_n].
*
* The stylePatterns is a list whose elements have the form
* [style : String, pattern : RegExp, context : RegExp, shortcut : String].
&
* Style is a style constant like PR_PLAIN.
*
* Pattern must only match prefixes, and if it matches a prefix and context is
* null or matches the last non-comment token parsed, then that match is
* considered a token with the same style.
*
* Context is applied to the last non-whitespace, non-comment token recognized.
*
* Shortcut is an optional string of characters, any of which, if the first
* character, gurantee that this pattern and only this pattern matches.
*
* @param {Array} shortcutStylePatterns patterns that always start with
* a known character. Must have a shortcut string.
* @param {Array} fallthroughStylePatterns patterns that will be tried in order
* if the shortcut ones fail. May have shortcuts.
*
* @return {function (sourceCode : String) -> Array.<Number|String>} a function
* that takes source code and a list of decorations to append to.
*/
function PR_createSimpleLexer(shortcutStylePatterns,
fallthroughStylePatterns) {
var shortcuts = {};
(function () {
var allPatterns = shortcutStylePatterns.concat(fallthroughStylePatterns);
for (var i = allPatterns.length; --i >= 0;) {
var patternParts = allPatterns[i];
var shortcutChars = patternParts[3];
if (shortcutChars) {
for (var c = shortcutChars.length; --c >= 0;) {
shortcuts[shortcutChars.charAt(c)] = patternParts;
}
}
}
})();
var nPatterns = fallthroughStylePatterns.length;
return function (sourceCode, opt_basePos) {
opt_basePos = opt_basePos || 0;
var decorations = [opt_basePos, PR_PLAIN];
var lastToken = '';
var pos = 0; // index into sourceCode
var tail = sourceCode;
while (tail.length) {
var style;
var token = null;
var patternParts = shortcuts[tail.charAt(0)];
if (patternParts) {
var match = tail.match(patternParts[1]);
token = match[0];
style = patternParts[0];
} else {
for (var i = 0; i < nPatterns; ++i) {
patternParts = fallthroughStylePatterns[i];
var contextPattern = patternParts[2];
if (contextPattern && !contextPattern.test(lastToken)) {
// rule can't be used
continue;
}
var match = tail.match(patternParts[1]);
if (match) {
token = match[0];
style = patternParts[0];
break;
}
}
if (!token) { // make sure that we make progress
style = PR_PLAIN;
token = tail.substring(0, 1);
}
}
decorations.push(opt_basePos + pos, style);
pos += token.length;
tail = tail.substring(token.length);
if (style !== PR_COMMENT && /\S/.test(token)) { lastToken = token; }
}
return decorations;
};
}
var PR_C_STYLE_STRING_AND_COMMENT_LEXER = PR_createSimpleLexer([
[PR_STRING, /^\'(?:[^\\\']|\\[\s\S])*(?:\'|$)/, null, "'"],
[PR_STRING, /^\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)/, null, '"'],
[PR_STRING, /^\`(?:[^\\\`]|\\[\s\S])*(?:\`|$)/, null, '`']
], [
[PR_PLAIN, /^(?:[^\'\"\`\/\#]+)/, null, ' \r\n'],
[PR_COMMENT, /^#[^\r\n]*/, null, '#'],
[PR_COMMENT, /^\/\/[^\r\n]*/, null],
[PR_STRING, /^\/(?:[^\\\*\/]|\\[\s\S])+(?:\/|$)/, REGEXP_PRECEDER_PATTERN],
[PR_COMMENT, /^\/\*[\s\S]*?(?:\*\/|$)/, null]
]);
/** splits the given string into comment, string, and "other" tokens.
* @param {String} sourceCode as plain text
* @return {Array.<Number|String>} a decoration list.
* @private
*/
function PR_splitStringAndCommentTokens(sourceCode) {
return PR_C_STYLE_STRING_AND_COMMENT_LEXER(sourceCode);
}
var PR_C_STYLE_LITERAL_IDENTIFIER_PUNC_RECOGNIZER = PR_createSimpleLexer([], [
[PR_PLAIN, /^\s+/, null, ' \r\n'],
// TODO(mikesamuel): recognize non-latin letters and numerals in identifiers
[PR_PLAIN, /^[a-z_$@][a-z_$@0-9]*/i, null],
// A hex number
[PR_LITERAL, /^0x[a-f0-9]+[a-z]/i, null],
// An octal or decimal number, possibly in scientific notation
[PR_LITERAL, /^(?:\d(?:_\d+)*\d*(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?[a-z]*/i,
null, '123456789'],
[PR_PUNCTUATION, /^[^\s\w\.$@]+/, null]
// Fallback will handle decimal points not adjacent to a digit
]);
/** splits plain text tokens into more specific tokens, and then tries to
* recognize keywords, and types.
* @private
*/
function PR_splitNonStringNonCommentTokens(source, decorations) {
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style === PR_PLAIN) {
var start = decorations[i];
var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
var chunk = source.substring(start, end);
var subDecs = PR_C_STYLE_LITERAL_IDENTIFIER_PUNC_RECOGNIZER(chunk, start);
for (var j = 0, m = subDecs.length; j < m; j += 2) {
var subStyle = subDecs[j + 1];
if (subStyle === PR_PLAIN) {
var subStart = subDecs[j];
var subEnd = j + 2 < m ? subDecs[j + 2] : chunk.length;
var token = source.substring(subStart, subEnd);
if (token == '.') {
subDecs[j + 1] = PR_PUNCTUATION;
} else if (token in PR_keywords) {
subDecs[j + 1] = PR_KEYWORD;
} else if (/^@?[A-Z][A-Z$]*[a-z][A-Za-z$]*$/.test(token)) {
// classify types and annotations using Java's style conventions
subDecs[j + 1] = token.charAt(0) == '@' ? PR_LITERAL : PR_TYPE;
}
}
}
PR_spliceArrayInto(subDecs, decorations, i, 2);
i += subDecs.length - 2;
}
}
return decorations;
}
var PR_MARKUP_LEXER = PR_createSimpleLexer([], [
[PR_PLAIN, /^[^<]+/, null],
[PR_DECLARATION, /^<!\w[^>]*(?:>|$)/, null],
[PR_COMMENT, /^<!--[\s\S]*?(?:-->|$)/, null],
[PR_SOURCE, /^<\?[\s\S]*?(?:\?>|$)/, null],
[PR_SOURCE, /^<%[\s\S]*?(?:%>|$)/, null],
[PR_SOURCE,
// Tags whose content is not escaped, and which contain source code.
/^<(script|style|xmp)\b[^>]*>[\s\S]*?<\/\1\b[^>]*>/i, null],
[PR_TAG, /^<\/?\w[^<>]*>/, null]
]);
// Splits any of the source|style|xmp entries above into a start tag,
// source content, and end tag.
var PR_SOURCE_CHUNK_PARTS = /^(<[^>]*>)([\s\S]*)(<\/[^>]*>)$/;
/** split markup on tags, comments, application directives, and other top level
* constructs. Tags are returned as a single token - attributes are not yet
* broken out.
* @private
*/
function PR_tokenizeMarkup(source) {
var decorations = PR_MARKUP_LEXER(source);
for (var i = 0; i < decorations.length; i += 2) {
if (decorations[i + 1] === PR_SOURCE) {
var start = decorations[i];
var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
// Split out start and end script tags as actual tags, and leave the body
// with style SCRIPT.
var sourceChunk = source.substring(start, end);
var match = (sourceChunk.match(PR_SOURCE_CHUNK_PARTS)
//|| sourceChunk.match(/^(<[?%])([\s\S]*)([?%]>)$/)
);
if (match) {
decorations.splice(
i, 2,
start, PR_TAG, // the open chunk
start + match[1].length, PR_SOURCE,
start + match[1].length + (match[2] || '').length, PR_TAG);
}
}
}
return decorations;
}
var PR_TAG_LEXER = PR_createSimpleLexer([
[PR_ATTRIB_VALUE, /^\'[^\']*(?:\'|$)/, null, "'"],
[PR_ATTRIB_VALUE, /^\"[^\"]*(?:\"|$)/, null, '"'],
[PR_PUNCTUATION, /^[<>\/=]+/, null, '<>/=']
], [
[PR_TAG, /^[\w-]+/, /^</],
[PR_ATTRIB_VALUE, /^[\w-]+/, /^=/],
[PR_ATTRIB_NAME, /^[\w-]+/, null],
[PR_PLAIN, /^\s+/, null, ' \r\n']
]);
/** split tags attributes and their values out from the tag name, and
* recursively lex source chunks.
* @private
*/
function PR_splitTagAttributes(source, decorations) {
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style === PR_TAG) {
var start = decorations[i];
var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
var chunk = source.substring(start, end);
var subDecorations = PR_TAG_LEXER(chunk, start);
PR_spliceArrayInto(subDecorations, decorations, i, 2);
i += subDecorations.length - 2;
}
}
return decorations;
}
/** identify regions of markup that are really source code, and recursivley
* lex them.
* @private
*/
function PR_splitSourceNodes(source, decorations) {
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style == PR_SOURCE) {
// Recurse using the non-markup lexer
var start = decorations[i];
var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
var subDecorations = PR_decorateSource(source.substring(start, end));
for (var j = 0, m = subDecorations.length; j < m; j += 2) {
subDecorations[j] += start;
}
PR_spliceArrayInto(subDecorations, decorations, i, 2);
i += subDecorations.length - 2;
}
}
return decorations;
}
/** identify attribute values that really contain source code and recursively
* lex them.
* @private
*/
function PR_splitSourceAttributes(source, decorations) {
var nextValueIsSource = false;
for (var i = 0; i < decorations.length; i += 2) {
var style = decorations[i + 1];
if (style === PR_ATTRIB_NAME) {
var start = decorations[i];
var end = i + 2 < decorations.length ? decorations[i + 2] : source.length;
nextValueIsSource = /^on|^style$/i.test(source.substring(start, end));
} else if (style == PR_ATTRIB_VALUE) {
if (nextValueIsSource) {
var start = decorations[i];
var end
= i + 2 < decorations.length ? decorations[i + 2] : source.length;
var attribValue = source.substring(start, end);
var attribLen = attribValue.length;
var quoted =
(attribLen >= 2 && /^[\"\']/.test(attribValue) &&
attribValue.charAt(0) === attribValue.charAt(attribLen - 1));
var attribSource;
var attribSourceStart;
var attribSourceEnd;
if (quoted) {
attribSourceStart = start + 1;
attribSourceEnd = end - 1;
attribSource = attribValue;
} else {
attribSourceStart = start + 1;
attribSourceEnd = end - 1;
attribSource = attribValue.substring(1, attribValue.length - 1);
}
var attribSourceDecorations = PR_decorateSource(attribSource);
for (var j = 0, m = attribSourceDecorations.length; j < m; j += 2) {
attribSourceDecorations[j] += attribSourceStart;
}
if (quoted) {
attribSourceDecorations.push(attribSourceEnd, PR_ATTRIB_VALUE);
PR_spliceArrayInto(attribSourceDecorations, decorations, i + 2, 0);
} else {
PR_spliceArrayInto(attribSourceDecorations, decorations, i, 2);
}
}
nextValueIsSource = false;
}
}
return decorations;
}
/** returns a list of decorations, where even entries
*
* This code treats ", ', and ` as string delimiters, and \ as a string escape.
* It does not recognize perl's qq() style strings. It has no special handling
* for double delimiter escapes as in basic, or tje tripled delimiters used in
* python, but should work on those regardless although in those cases a single
* string literal may be broken up into multiple adjacent string literals.
*
* It recognizes C, C++, and shell style comments.
*
* @param {String} sourceCode as plain text
* @return {Array.<String,Number>} a decoration list
*/
function PR_decorateSource(sourceCode) {
// Split into strings, comments, and other.
// We do this because strings and comments are easily recognizable and can
// contain stuff that looks like other tokens, so we want to mark those early
// so we don't recurse into them.
var decorations = PR_splitStringAndCommentTokens(sourceCode);
// Split non comment|string tokens on whitespace and word boundaries
decorations = PR_splitNonStringNonCommentTokens(sourceCode, decorations);
return decorations;
}
/** returns a decoration list given a string of markup.
*
* This code recognizes a number of constructs.
* <!-- ... --> comment
* <!\w ... > declaration
* <\w ... > tag
* </\w ... > tag
* < ?...?> embedded source
* <%...%> embedded source
* &[#\w]...; entity
*
* It does not recognizes %foo; doctype entities from .
*
* It will recurse into any <style>, <script>, and on* attributes using
* PR_lexSource.
*/
function PR_decorateMarkup(sourceCode) {
// This function works as follows:
// 1) Start by splitting the markup into text and tag chunks
// Input: String s
// Output: List<PR_Token> where style in (PR_PLAIN, null)
// 2) Then split the text chunks further into comments, declarations,
// tags, etc.
// After each split, consider whether the token is the start of an
// embedded source section, i.e. is an open <script> tag. If it is,
// find the corresponding close token, and don't bother to lex in between.
// Input: List<String>
// Output: List<PR_Token> with style in (PR_TAG, PR_PLAIN, PR_SOURCE, null)
// 3) Finally go over each tag token and split out attribute names and values.
// Input: List<PR_Token>
// Output: List<PR_Token> where style in
// (PR_TAG, PR_PLAIN, PR_SOURCE, NAME, VALUE, null)
var decorations = PR_tokenizeMarkup(sourceCode);
decorations = PR_splitTagAttributes(sourceCode, decorations);
decorations = PR_splitSourceNodes(sourceCode, decorations);
decorations = PR_splitSourceAttributes(sourceCode, decorations);
return decorations;
}
/**
* @param {String} sourceText plain text
* @param {Array.<Number|String>} extractedTags chunks of raw html preceded by
* their position in sourceText in order.
* @param {Array.<Number|String> decorations style classes preceded by their
* position in sourceText in order.
* @return {String} html
* @private
*/
function PR_recombineTagsAndDecorations(
sourceText, extractedTags, decorations) {
var html = [];
var outputIdx = 0; // index past the last char in sourceText written to html
var openDecoration = null;
var currentDecoration = null;
var tagPos = 0; // index into extractedTags
var decPos = 0; // index into decorations
var tabExpander = PR_tabExpander(PR_TAB_WIDTH);
// A helper function that is responsible for opening sections of decoration
// and outputing properly escaped chunks of source
function emitTextUpTo(sourceIdx) {
if (sourceIdx > outputIdx) {
if (openDecoration && openDecoration !== currentDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
if (!openDecoration && currentDecoration) {
openDecoration = currentDecoration;
html.push('<span class="', openDecoration, '">');
}
// This interacts badly with some wikis which introduces paragraph tags
// into pre blocks for some strange reason.
// It's necessary for IE though which seems to lose the preformattednes
// of <pre> tags when their innerHTML is assigned.
// http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html
// and it serves to undo the conversion of <br>s to newlines done in
// chunkify.
var htmlChunk = PR_textToHtml(
tabExpander(sourceText.substring(outputIdx, sourceIdx)))
.replace(/(\r\n?|\n| ) /g, '$1 ')
.replace(/\r\n?|\n/g, '<br>');
html.push(htmlChunk);
outputIdx = sourceIdx;
}
}
while (true) {
// Determine if we're going to consume a tag this time around. Otherwise we
// consume a decoration or exit.
var outputTag;
if (tagPos < extractedTags.length) {
if (decPos < decorations.length) {
// Pick one giving preference to extractedTags since we shouldn't open
// a new style that we're going to have to immediately close in order
// to output a tag.
outputTag = extractedTags[tagPos] <= decorations[decPos];
} else {
outputTag = true;
}
} else {
outputTag = false;
}
// Consume either a decoration or a tag or exit.
if (outputTag) {
emitTextUpTo(extractedTags[tagPos]);
if (openDecoration) {
// Close the current decoration
html.push('</span>');
openDecoration = null;
}
html.push(extractedTags[tagPos + 1]);
tagPos += 2;
} else if (decPos < decorations.length) {
emitTextUpTo(decorations[decPos]);
currentDecoration = decorations[decPos + 1];
decPos += 2;
} else {
break;
}
}
emitTextUpTo(sourceText.length);
if (openDecoration) {
html.push('</span>');
}
return html.join('');
}
/** pretty print a chunk of code.
*
* @param {String} sourceCodeHtml code as html
* @return {String} code as html, but prettier
*/
function prettyPrintOne(sourceCodeHtml) {
try {
// Extract tags, and convert the source code to plain text.
var sourceAndExtractedTags = PR_extractTags(sourceCodeHtml);
/** Plain text. @type {String} */
var source = sourceAndExtractedTags.source;
/** Even entries are positions in source in ascending order. Odd entries
* are tags that were extracted at that position.
* @type {Array.<Number|String>}
*/
var extractedTags = sourceAndExtractedTags.tags;
// Pick a lexer and apply it.
/** Treat it as markup if the first non whitespace character is a < and the
* last non-whitespace character is a >.
* @type {Boolean}
*/
var isMarkup = /^\s*</.test(source) && />\s*$/.test(source);
/** Even entires are positions in source in ascending order. Odd enties are
* style markers (e.g., PR_COMMENT) that run from that position until the
* end.
* @type {Array.<Number|String>}
*/
var decorations = isMarkup
? PR_decorateMarkup(source)
: PR_decorateSource(source);
// Integrate the decorations and tags back into the source code to produce
// a decorated html string.
return PR_recombineTagsAndDecorations(source, extractedTags, decorations);
} catch (e) {
if ('console' in window) {
console.log(e);
console.trace();
}
return sourceCodeHtml;
}
}
var PR_SHOULD_USE_CONTINUATION = true;
/** find all the < pre > and < code > tags in the DOM with class=prettyprint and
* prettify them.
* @param {Function} opt_whenDone if specified, called when the last entry
* has been finished.
*/
function prettyPrint(opt_whenDone) {
// fetch a list of nodes to rewrite
var codeSegments = [
document.getElementsByTagName('pre'),
document.getElementsByTagName('code'),
document.getElementsByTagName('xmp') ];
var elements = [];
for (var i = 0; i < codeSegments.length; ++i) {
for (var j = 0; j < codeSegments[i].length; ++j) {
elements.push(codeSegments[i][j]);
}
}
codeSegments = null;
// the loop is broken into a series of continuations to make sure that we
// don't make the browser unresponsive when rewriting a large page.
var k = 0;
function doWork() {
var endTime = (PR_SHOULD_USE_CONTINUATION
? new Date().getTime() + 250
: Infinity);
for (; k < elements.length && new Date().getTime() < endTime; k++) {
var cs = elements[k];
if (cs.className && cs.className.indexOf('prettyprint') >= 0) {
// make sure this is not nested in an already prettified element
var nested = false;
for (var p = cs.parentNode; p != null; p = p.parentNode) {
if ((p.tagName == 'pre' || p.tagName == 'code' ||
p.tagName == 'xmp') &&
p.className && p.className.indexOf('prettyprint') >= 0) {
nested = true;
break;
}
}
if (!nested) {
// fetch the content as a snippet of properly escaped HTML.
// Firefox adds newlines at the end.
var content = PR_getInnerHtml(cs);
content = content.replace(/(?:\r\n?|\n)$/, '');
// do the pretty printing
var newContent = prettyPrintOne(content);
// push the prettified html back into the tag.
if (!PR_isRawContent(cs)) {
// just replace the old html with the new
cs.innerHTML = newContent;
} else {
// we need to change the tag to a <pre> since <xmp>s do not allow
// embedded tags such as the span tags used to attach styles to
// sections of source code.
var pre = document.createElement('PRE');
for (var i = 0; i < cs.attributes.length; ++i) {
var a = cs.attributes[i];
if (a.specified) {
pre.setAttribute(a.name, a.value);
}
}
pre.innerHTML = newContent;
// remove the old
cs.parentNode.replaceChild(pre, cs);
}
}
}
}
if (k < elements.length) {
// finish up in a continuation
setTimeout(doWork, 250);
} else if (opt_whenDone) {
opt_whenDone();
}
}
doWork();
}
</script>
Step 3: Place HTML below in your BODY section
HTML
Code:
<div style="width: 400px; margin-left: 10%">
<strong>JavaScript</strong><br>
<pre class="prettyprint" id="javascript">
/**
* nth element in the fibonacci series.
* @param n >= 0
* @return the nth element, >= 0.
*/
function fib(n) {
var a = 1, b = 1;
var tmp;
while (--n >= 0) {
tmp = a;
a += b;
b = tmp;
}
return a;
}
document.write(fib(10));
</pre>
<strong>PHP</strong><br>
<pre class="prettyprint" id="php">
<html>
<head>
<title><?= 'Fibonacci numbers' ?></title>
<?php
// PHP has a plethora of comment types
/* What is a
"plethora"? */
function fib($n) {
# I don't know.
$a = 1;
$b = 1;
while (--$n >= 0) {
echo "$a\n";
$tmp = $a;
$a += $b;
$b = $tmp;
}
}
?>
</head>
<body>
<?= fib(10) ?>
</body>
</html>
</pre>
<strong>HTML</strong><br>
<pre class="prettyprint" id="javascript">
<html>
<head>
<title>Fibonacci number</title>
</head>
<body>
<noscript>
<dl>
<dt>Fibonacci numbers</dt>
<dd>1</dd>
<dd>1</dd>
<dd>2</dd>
<dd>3</dd>
<dd>5</dd>
<dd>8</dd>
…
</dl>
</noscript>
<script type="text/javascript"><!--
function fib(n) {
var a = 1, b = 1;
var tmp;
while (--n >= 0) {
tmp = a;
a += b;
b = tmp;
}
return a;
}
document.writeln(fib(10));
// -->
</script>
</body>
</html>
</pre>
</div>
<strong>In Sentences</strong><br>
<p>
Lorem ipsum dolor sit amet, <code class="prettyprint" id="html"><script type="text/javascript"></code> consectetuer adipiscing elit. Ma quande <code class="prettyprint" id="javascript">function lingues()</code> coalesce, li grammatica del resultant.</p>
</p>
</div>
<script type="text/javascript">
// 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() {
prettyPrint();
});</script>
-
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: 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
*/
-->
<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>
-
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: CSS below for styling thescript, place it into 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: Copy & Paste JavaScript code below in your HEAD section
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 "Save"</p>
<div id="box"></div>
<input name="" type="text" /><input id="save_button" name="save_button" type="button" value="save"/>
Step 4: Download files below
Files
mootools.js
-
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
-
Calc4Chem: Awesome Scientific Calculator with Physical and Chemical constants
This is an amazing JavaScript calculator script that can be used as a common scientific calculator (with functions of sin, cos, log, ... 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">
/*
This script downloaded from www.JavaScriptBank.com
Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
/* --------------------------------------------------------- */
/* Calc4Chem */
/* --------------------------------------------------------- */
#calc4chem {
position: relative;
top: 15px;
width: 529px;
height: 377px;
margin: auto;
border: 3px outset;
background: #e4e4e4;
text-align: center;
color: #eee;
}
#kalkulator {
position: absolute;
top: 3px;
left: 3px;
width: 257px;
height: 365px;
border: 0px ridge #f00;
background: #e4e4e4;
color: #fff;
}
#biljeska {
position: absolute;
top: 3px;
left: 267px;
width: 256px;
height: 365px;
border: 0px ridge #999;
background: #e4e4e4;
color: #fff;
}
#konstante {
position: absolute;
top: 13px;
left: 275px;
width: 245px;
height: 350px;
border: 1px ridge #999;
background: #fff;
color: #fff;
display: none;
/*visibility: hidden; visible hidden */
text-align: center;
overflow: auto;
}
#numformat {
position: absolute;
top: 138px;
left: 3px;
width: 245px;
height: 225px;
border: 1px ridge #999;
display: none;
background: #e4e4e4;
color: #fff;
}
.constnaslov {
width: 200px;
color: #00f;
text-align: center;
font: normal 12px/125% sans-serif;
margin: 5px;
padding-bottom: 5px;
border-bottom: 1px #cacaba solid;
}
.const {
width: 200px;
text-align: center;
font: 11px/125% sans-serif;
margin: 5px;
padding-bottom: 5px;
border-bottom: 1px #cacaba solid;
}
.const a:link {
display: block;
color: #900;
text-decoration: none;
}
.const a:visited {
display: block;
color: #036;
text-decoration: none;
}
.const a:active {
display: block;
color: #900;
text-decoration: none;
}
.const a:hover {
display: block;
background: #eaeafa;
color: #900;
text-decoration: none;
}
.crta {
position: absolute;
top: 0px;
left: 262px;
width: 2px;
height: 372px;
border: 2px inset;
background: #fff; /* groove ridge */
color: #fff;
}
.tipkovnica {
position: absolute;
top: 138px;
left: 5px;
width: 245px;
height: 228px;
background: #e4e4e4;
}
.displej {
position: absolute;
top: 10px;
left: 6px;
width: 240px;
height: 82px;
border: 2px ridge #eee;
background: #eee;
}
#numauto, #numsci, #numfix, #nummem, #numrad, #numdeg, #numgrad {
position: absolute;
margin-top: 2px;
width: 26px;
height: 10px;
font: normal 9px sans-serif;
color: #ccc;
display: inline;
border: 0px solid #e00;
background: #eee;
}
#numauto {
left: 5px;
color: #000;
}
#numsci {
left: 37px;
}
#numfix {
left: 62px;
}
#nummem {
left: 107px;
}
#numrad {
left: 154px;
color: #000;
}
#numdeg {
left: 180px;
}
#numgrad {
left: 205px;
}
.upit {
position: absolute;
top: 27px;
left: 6px;
width: 225px;
height: 25px;
border: 0px;
background: #eee;
text-align: left;
font: normal 9pt sans-serif;
letter-spacing: 1px;
color: #0a0;
}
.rezultat {
position: absolute;
top: 52px;
left: 6px;
width: 225px;
height: 25px;
border: 0px;
background: #eee;
text-align: right;
font: bold 12pt sans-serif;
letter-spacing: 1px;
color: #00a;
}
.formatbr {
position: absolute;
top: 35px;
left: 12px;
width: 220px;
height: 95px;
border: 1px solid #cdcdcd;
background: #e8e8e8;
}
.formatnaslov {
position: relative;
margin-top: 5px;
font: normal 12pt cursive;
text-align: center;
}
.automatik, .scienc, .fiksed {
position: absolute;
left: 6px;
font: normal 10pt sans-serif;
}
.automatik {top: 10px;}
.scienc {top: 38px;}
.fiksed {top: 66px;}
.decnaslov {
position: absolute;
top: 10px;
left: 110px;
width: 110px;
text-align: center;
font: normal 10pt sans-serif;
color: #000;
border: 0px solid #cdcdcd;
}
.decimal {
position: absolute;
top: 32px;
left: 136px;
width: 60px;
height: 22px;
}
.separator {
position: absolute;
top: 70px;
left: 65px;
width: 150px;
text-align: right;
font: normal 10pt sans-serif;
color: #000;
border: 0px solid #cdcdcd;
}
.rad {
position: absolute;
top: 140px;
left: 12px;
width: 220px;
height: 21px;
border: 1px solid #cdcdcd;
background: #e8e8e8;
}
.deg {
position: relative;
margin: 4px;
top: -1px;
font: normal 10pt sans-serif;
}
.cls {
position: absolute;
top: 103px;
left: 217px;
width: 30px;
height: 22px;
color: #f00;
display: none;
}
.zadatak {
position: absolute;
top: 98px;
left: 6px;
width: 240px;
height: 28px;
border: 2px groove #eee;
background: #fff;
}
.unos {
position: absolute;
top: 1px;
left: 4px;
width: 228px;
height: 23px;
border: 0px;
font: bold 10pt cursive;
color: #060;
}
.tekstarea {
position: absolute;
top: 10px;
left: 8px;
width: 238px;
height: 317px;
padding: 0px 0px 0px 5px;
border: 2px groove #ccc;
background: #fff; /*plavo*/
font: normal 9pt/150% monospace;
color: #345678;
overflow: auto;
}
.n1, .n2, .n3, .n4 {
position: absolute;
top: 340px;
height: 24px;
width: 80px;
font: normal 9pt sans-serif;
color: #000;
}
.n1 {
left: 8px;
}
.n2 {
left: 91px;
}
.n3 {
left: 174px;
}
.n4 {
top: 174px;
left: 85px;
}
.n2copy {
position: absolute;
left: 0px;
top: 206px;
width: 242px;
color: #aaa;
font: normal 9pt sans-serif;
text-align: center;
}
.b11, .b12, .b13, .b14, .b15, .b16, .b21, .b22, .b23, .b24, .b25, .b26, .b31, .b32, .b33, .b34, .b35, .b36 {
position: absolute;
height: 25px;
width: 40px;
padding: 0px;
color: #000;
font: normal 10pt monospace;
}
.b41, .b42, .b43, .b44, .b45, .b46, .b51, .b52, .b53, .b54, .b55, .b56, .b61, .b62, .b63, .b64, .b65, .b66, .b71, .b72, .b73, .b74, .b75, .b76 {
position: absolute;
height: 35px;
width: 40px;
padding: 0px;
color: #000;
}
.b55, .b75 {
position: absolute;
height: 35px;
width: 81px;
font: normal 10pt sans-serif;
color: #000;
}
.b75 {
position: absolute;
height: 35px;
width: 81px;
font: normal 15pt sans-serif;
color: #050;
}
.b45, .b46 {
font: normal 10pt sans-serif;
color: #a00;
}
.b34 {
font: normal 10pt sans-serif;
}
.b44, .b54, .b74 {
font: bold 13pt sans-serif;
color: #00f;
}
.b64 {
font: normal 15pt serif;
color: #00f;
}
.b41, .b42, .b43, .b51, .b52, .b53, .b61, .b62, .b63, .b71, .b72 {
font: normal 12pt cursive;
color: #575;
}
.b11, .b12, .b13, .b14, .b15, .b16 {
top: 0px;
}
.b21, .b22, .b23, .b24, .b25, .b26 {
top: 26px;
}
.b31, .b32, .b33, .b34, .b35, .b36 {
top: 52px;
}
.b41, .b42, .b43, .b44, .b45, .b46 {
top: 85px;
}
.b51, .b52, .b53, .b54, .b55, .b56 {
top: 121px;
}
.b61, .b62, .b63, .b64, .b65, .b66 {
top: 156px;
}
.b71, .b72, .b73, .b74, .b75, .b76 {
top: 192px;
}
.b11, .b21, .b31, .b41, .b51, .b61, .b71 {
left: 0px
}
.b12, .b22, .b32, .b42, .b52, .b62, .b72 {
left: 41px
}
.b13, .b23, .b33, .b43, .b53, .b63, .b73 {
left: 82px
}
.b14, .b24, .b34, .b44, .b54, .b64, .b74 {
left: 123px
}
.b15, .b25, .b35, .b45, .b55, .b65, .b75 {
left: 164px
}
.b16, .b26, .b36, .b46, .b56, .b66, .b76 {
left: 205px
}
/* END of Calc4Chem */
/* --------------------------------------------------------- */
/*Eni Generalic, Split, Create: 1999/10/14; Update: 2008/02/27 */
/* Copyright © 2008 by EniG. */
</style>
Step 2: Use JavaScript code below to setup the script
JavaScript
Code:
<script type="text/javascript">
// Created by: Eni Generalic | http://www.periodni.com/
// This script downloaded from www.JavaScriptBank.com
// Scientific Calculator written by Eni Generalic - http://www.periodni.com/
// Copyright © 2008 by EniG. If you use a variant of this in your page, please email me at eni.generalic@gmail.com
// Eni Generalic, Split, Create: 1999/10/14; Update: 2008/03/01
// Atomic Weights of the Elements 2005, Pure & Appl. Chem., Vol. 78, No. 11, (2006) 2051-2066).
var EniG = " Calc4Chem - www.periodni.com";
var que = "";
var ans = 0;
var mem = 0;
var broj = "0";
var tocka = 0;
var eksp = 0;
var baza = "";
var eksponent = 3;
var rjesenje = 0;
var decimala = 14;
var asf = 0;
var rdg = 0;
var sep1000 = 0;
var enter = "";
var mr = "";
var pi = 3.141592653589793;
var e = 2.71828182845905;
var abc = "";
//window.onerror = handleError;
function start(){
enter = "\r\n";
mr = document.racunalo.memorija.value;
document.racunalo.notes.value = enter + EniG + enter;
var dan = new Date();
document.racunalo.notes.value += " " + dan.toLocaleString() + enter + enter;
document.racunalo.zadatak.focus();
}
function handleError() {
//alert("YOU HAVE ENCOUNTERED A JAVASCRIPT ERROR");
document.racunalo.notes.value += " = Syntax Error\r\n";
document.racunalo.rezultat.value = "Syntax Error";
document.racunalo.zadatak.focus();
return true;
}
function memory(operator) {
switch(operator) {
case 1: // MS
memorija = document.racunalo.rezultat.value;
memorija = memorija.replace(/ /g,'');
document.racunalo.memorija.value = memorija;
document.racunalo.MR.title = mr + " (" + memorija + ")";
mem = parseFloat(memorija);
stanje = (document.getElementById('nummem').style.color == '#000') ? '#ccc' : '#000';
document.getElementById('nummem').style.color = stanje;
break;
case 2: // MR
var memorija = document.racunalo.memorija.value;
if (memorija==0 || slovo(memorija.charAt(0))) {memorija = ""}
document.racunalo.zadatak.value += memorija;
break;
case 3: // CLS
if (document.racunalo.zadatak.value == "") {document.racunalo.rezultat.value = "";}
else {document.racunalo.zadatak.value = ""; }
break;
case 4: // Mode
vidi('numformat');
break;
case 5: // Reset
document.racunalo.notes.value = enter + EniG + enter;
document.racunalo.memorija.value = "";
document.racunalo.MR.title = mr;
decimala = 14;
asf = 0;
rdg = 0;
sep1000 = 0;
mem = 0;
ans = 0;
document.getElementById('numauto').style.color = '#000';
document.getElementById('numsci').style.color = '#ccc';
document.getElementById('numfix').style.color = '#ccc';
document.getElementById('nummem').style.color = '#ccc';
document.getElementById('numrad').style.color = '#000';
document.getElementById('numdeg').style.color = '#ccc';
document.getElementById('numgrad').style.color = '#ccc';
break;
}
document.racunalo.zadatak.focus();
}
function dodajBroj(noviznak) {
document.racunalo.zadatak.focus();
document.racunalo.zadatak.value += noviznak
}
function dodajConst(noviznak) {
document.racunalo.zadatak.focus();
document.racunalo.zadatak.value += noviznak;
vidi('konstante')
}
function izracunaj(zarez) {
var pitanje = "";
var odgovor = "";
var mem = 0;
//onerror = handleError;
if (zarez >= 1) {
if (document.racunalo.zadatak.value == "") {
broj = document.racunalo.rezultat.value;
}
else {
broj = document.racunalo.zadatak.value;
if (ubacirezultat(broj.charAt(0))) {
broj = document.racunalo.rezultat.value + broj;
}
}
}
for (var i=0; i<broj.length; i++) {
var mm = broj.charAt(i);
var mmup = broj.charAt(i+1);
var mmdn = broj.charAt(i-1);
if (mm == ",") {mm = ".";}
else if (mm == "}" || mm == "]") {mm = ")";}
else if (mm == "{" || mm == "[") {mm = "(";}
else if (mm == " " || mm == "=") {mm = "";}
else if (mm == "*" && mmup == "*") {mm = "^"; i += 1;}
else if (mm == "+" && mmup == "-") {mm = "-"; i += 1;}
else if (mm == "E" && kemilimat(mmup)) {mm = "e";}
if (mm == "." && BrojAtoma(mmdn)==false) {mm = "0.";}
else if (velikoslovo(mm)) {var kem = 1;}
if (pitanje == "0") {
if (operator(mm)) {}
else if (mm != ".") {pitanje = "";}
}
//if (i == 0) {
// if (mm == "0" && mmup == "0") {mm = "";}
//}
pitanje += mm;
}
if (zarez == 1) {
document.racunalo.notes.value += pitanje;
document.racunalo.upit.value = pitanje;
if (kem == 1) {
//var atom = "+" + pitanje;
odgovor = masa(pitanje);
}
else {
odgovor = zagrada(pitanje);
}
}
else {
odgovor = matematika(zarez, pitanje)
}
odgovor = odgovor.toString();
document.racunalo.oldrezultat.value = odgovor;
ans = parseFloat(odgovor);
izgledbroja(odgovor);
document.racunalo.zadatak.value = "";
document.racunalo.zadatak.focus();
}
function matematika(zarez, rjesenje) {
var pitanje = "";
with (Math) {
if (zarez == 2) {
pitanje = rjesenje + "^2";
rjesenje = pow(rjesenje, 2)
}
else if (zarez == 3) {
pitanje = rjesenje + "^(1/2)";
rjesenje = sqrt(rjesenje)
}
else if (zarez == 4) {
pitanje = rjesenje + "*(-1)";
rjesenje = -rjesenje
}
else if (zarez == 5) {
pitanje = "ln(" + rjesenje + ")";
rjesenje = log(rjesenje)
}
else if (zarez == 6) {
pitanje = "e^" + rjesenje;
rjesenje = pow(E, rjesenje)
}
else if (zarez == 7) {
pitanje = "1/" + rjesenje;
rjesenje = 1/rjesenje
}
else if (zarez == 8) {
pitanje = "log(" + rjesenje + ")";
rjesenje = log(rjesenje)/LN10
}
else if (zarez == 9) {
pitanje = "10^" + rjesenje;
rjesenje = pow(10, rjesenje)
}
else if (zarez >= 10 && zarez <= 12) {
if (zarez == 10) {
pitanje = "atan(" + rjesenje + ")";
rjesenje = atan(rjesenje)
}
else if (zarez == 11) {
pitanje = "acos(" + rjesenje + ")";
rjesenje = acos(rjesenje)
}
else if (zarez == 12) {
pitanje = "asin(" + rjesenje + ")";
rjesenje = asin(rjesenje)
}
if (document.racunalo.stupnjevi[1].checked) {rjesenje = (rjesenje * 180) / PI}
else if (document.racunalo.stupnjevi[2].checked) {rjesenje = (rjesenje * 200) / PI}
}
else if (zarez >= 14 && zarez <= 16) {
if (document.racunalo.stupnjevi[1].checked)
{radijani = (rjesenje / 180) * PI}
else if (document.racunalo.stupnjevi[2].checked)
{radijani = (rjesenje / 200) * PI}
else
{radijani = rjesenje}
if (zarez == 14) {
pitanje = "tan(" + rjesenje + ")";
rjesenje = tan(radijani)
}
else if (zarez == 15) {
pitanje = "cos(" + rjesenje + ")";
rjesenje = cos(radijani)
}
else if (zarez == 16) {
pitanje = "sin(" + rjesenje + ")";
rjesenje = sin(radijani)
}
}
else if (zarez == 17) {
pitanje = rjesenje + "%";
rjesenje = rjesenje/100
}
else if (zarez == 18) {
pitanje = rjesenje + "ppm";
rjesenje = rjesenje/1000000
}
else if (zarez == 20) {
pitanje = rjesenje + "!";
rjesenje = factorial(rjesenje)
}
else if (zarez == 21) {
eksponent = prompt("Unesite eksponent / Please enter exponent", 3);
pitanje = rjesenje + "^" + eksponent;
rjesenje = pow(rjesenje, eksponent)
}
else if (zarez == 22) {
eksponent = prompt("Unesite korijen / Please enter root", 3);
document.racunalo.notes.value += rjesenje + "^(1/" + eksponent + ")";
rjesenje = pow(rjesenje, (1/eksponent))
}
}
document.racunalo.notes.value += pitanje;
document.racunalo.upit.value = pitanje;
return rjesenje;
}
function zagrada(xbroj) {
var intZagClose = 0
var intZagOpen = 0
var intXbroj = 0
var strNoviXbroj = ""
var strNoviZbroj = "";
do {
//document.racunalo.notes.value += enter + "intXbroj = " + intXbroj; 2+(2*(2+4)+3)^3+5
xbroj = xbroj.replace(/--/g,"-1*-");
intZagClose = xbroj.indexOf(")");
if (intZagClose != -1) {
for (var i = intZagClose; i >= 0; i--) {
if (xbroj.charAt(i)=="(") {
intZagOpen = i;
strNoviZbroj = xbroj.substring(intZagOpen+1,intZagClose);
break;
}
}
}
else {
strNoviZbroj = xbroj;
}
strNoviZbroj = strNoviZbroj + "*1";
strNoviZbroj = postotak(strNoviZbroj);
strNoviZbroj = trigonometrija(strNoviZbroj);
strNoviZbroj = logaritam(strNoviZbroj);
strNoviZbroj = potencija(strNoviZbroj);
strNoviZbroj = racun(strNoviZbroj);
if (intZagClose != -1) {
xbroj = xbroj.replace(xbroj.substring(intZagOpen, intZagClose+1), strNoviZbroj);
}
else {
xbroj = strNoviZbroj;
}
}
while (intZagClose > 0)
return xbroj;
}
function racun(zbroj) {
with (Math) {zbroj = eval(zbroj);}
return zbroj;
}
function potencija(ulaz) {
var intZagClose = 0
var intZagOpen = 0;
var intXbroj = ulaz.indexOf("^"); //2+2^3+2,15^2+4
while (intXbroj > 0) {
for (var i = intXbroj - 1; i >= 0; i--) {
if (operator(ulaz.charAt(i)) && ulaz.charAt(i-1)!="e") {
//if (i > 0 && operator(ulaz.charAt(i-1))) {
intZagOpen = i+1;
break;
}
}
if (ulaz.charAt(i) == "-"){
if (i == 0) {intZagOpen = 0;}
else if (i > 0 && operator(ulaz.charAt(i-1))) {intZagOpen = i;}
}
var strNoviXbroj = ulaz.substring(intZagOpen,intXbroj);
for (var i = intXbroj + 2; i < ulaz.length; i++) {
if (operator(ulaz.charAt(i)) && ulaz.charAt(i-1)!="e") {intZagClose = i-1; break}
}
var strNoviYbroj = ulaz.substring(intXbroj+1,intZagClose+1);
if (strNoviXbroj == 'e') {strNoviXbroj = e}; //cps
with (Math) {
intXbroj = pow(strNoviXbroj, strNoviYbroj);
}
//if (i != 0 && ulaz.charAt(i-1)) {} // za negativne brojeve -3^2 = -9 ili 9
ulaz = ulaz.replace(ulaz.substring(intZagOpen, intZagClose+1), intXbroj);
intXbroj = ulaz.indexOf("^");
}
return ulaz;
}
function postotak(ulaz) {
var intZagClose = 0;
var intZagOpen = 0;
var strDesnoFun = new Array ("!", "%");
for (var f = 0; f < 2; f++) {
var intXbroj = ulaz.indexOf(strDesnoFun[f]);
while (intXbroj > 0) {
for (var i = intXbroj - 1; i >= 0; i--) {
if (operator(ulaz.charAt(i)) && ulaz.charAt(i-1)!="e") {intZagOpen = i+1; break}
}
var strNoviXbroj = ulaz.substring(intZagOpen,intXbroj);
intZagClose = intXbroj+1;
with (Math) {
if (f == 0) {
intXbroj = factorial(strNoviXbroj);
}
else {
intXbroj = strNoviXbroj/100;
}
}
ulaz = ulaz.replace(ulaz.substring(intZagOpen, intZagClose), intXbroj);
intXbroj = ulaz.indexOf(strDesnoFun[f]);
}
}
return ulaz;
}
function trigonometrija(kut) {
var intZagClose = 0
var intKut = 0
var strNoviKut = ""
var strKrozPi = ")"
var strPiKroz = ")";
switch(rdg) {
case 1:
strKrozPi = ")*180/pi";
strPiKroz = "*pi/180)";
break;
case 2:
strKrozPi = ")*200/pi";
strPiKroz = "*pi/200)";
break;
default:
strKrozPi = ")";
strPiKroz = ")";
}
var strTrigFun = new Array ("sin", "cos", "tan");
for (var f = 0; f < 3; f++) {
intKut = kut.indexOf(strTrigFun[f]);
if (intKut >= 0) {
do {
//document.racunalo.notes.value += enter + intKut + enter; cos(2*(3+5)+3*(2+4))+1 2+(2*(2+cos(4))+3)+(3^3+5)*4
intZagClose = kut.length;
for (var i = intKut+4; i < intZagClose; i++) {
if (operator(kut.charAt(i)) && kut.charAt(i-1)!="e") {
intZagClose = i;
strNoviKut = kut.substring(intKut+3, intZagClose);
break;
}
}
if (intKut>0 && kut.charAt(intKut-1)=="a") {
intKut = intKut - 1;
strNoviKut = "a" + strTrigFun[f] + "(" + strNoviKut + strKrozPi;
}
else {
strNoviKut = strTrigFun[f] + "(" + strNoviKut + strPiKroz;
}
strNoviKut = racun(strNoviKut);
strNoviKut = Math.round(strNoviKut * Math.pow(10,14)) / Math.pow(10,14);
kut = kut.replace(kut.substring(intKut, intZagClose), strNoviKut);
intKut = kut.indexOf(strTrigFun[f]);
}
while (intKut != -1);
}
}
return kut;
}
function logaritam(kut) {
var intZagClose = 0
var intKut = 0
var strNoviKut = ""
var strKrozPi = ")"
var strPiKroz = ")";
// var e = 2.71828182845905
var strLogFun = new Array ("ln", "log");
for (var f = 0; f < 2; f++) {
intKut = kut.indexOf(strLogFun[f]);
if (intKut >= 0) {
do {
intZagClose = kut.length;
for (var i = intKut; i < intZagClose; i++) {
if (operator(kut.charAt(i)) && kut.charAt(i-1)!="e") {
intZagClose = i;
strNoviKut = kut.substring(intKut+strLogFun[f].length, intZagClose);
break;
}
}
if (f == 0) {
if (intKut>0 && kut.charAt(intKut-1)=="a") {
intKut = intKut - 1;
strNoviKut = "pow(E," + strNoviKut + ")";
}
else {
strNoviKut = "log(" + strNoviKut + ")";
}
}
else {
if (intKut>0 && kut.charAt(intKut-1)=="a") {
intKut = intKut - 1;
strNoviKut = "pow(10," + strNoviKut + ")";
}
else {
strNoviKut = "log(" + strNoviKut + ")/LN10";
}
}
strNoviKut = racun(strNoviKut);
kut = kut.replace(kut.substring(intKut, intZagClose), strNoviKut);
intKut = kut.indexOf(strLogFun[f]);
}
while (intKut != -1);
}
}
return kut;
}
function izazareza(novibroj) {
with (Math) {
if (eksp == -1) {
var duzina = tocka;
if (duzina == -1) {duzina = novibroj.length}
var desni = "";
if (duzina > 16) {
var privremeni = round(novibroj*pow(10, 16)) + " ";
var novie = privremeni.indexOf("e");
var lijevi = (privremeni.substring(0,novie));
lijevi = round(lijevi*pow(10, 15))/pow(10, 15) + " ";
desni = (privremeni.substring(novie+2,privremeni.length-1));
desni = "e+" + (desni-18);
}
else {
var lijevi = round(novibroj*pow(10, decimala))/pow(10, decimala) + " ";
}
}
else {
var lijevi = novibroj.substring(0,eksp);
var desni = novibroj.substring(eksp,novibroj.length);
lijevi = round(lijevi*pow(10, decimala))/pow(10, decimala) + " ";
}
lijevi = lijevi.substring(0,lijevi.length - 1);
if (lijevi.charAt(0) == ".") {lijevi = "0" + lijevi;}
if (decimala < 14) {
if (lijevi.indexOf(".") == -1 && decimala != 0) {lijevi += "."}
var nula = (tocka + decimala) - (lijevi.length - 1);
if (nula > 0 && decimala > 0) {
for (var n = 0; n < nula; n++) {
lijevi += "0";
}
}
}
return (lijevi + desni);
}
}
function factorial(n) {
if ((n == 0) || (n == 1)) {
return 1;
}
else {
var odgovor = (n * factorial(n-1));
return odgovor;
}
}
function masa(atom) {
with (Math) {
var atominfo = false;
var mm="";
var mmdn="";
var mmup="";
var znak="";
var izraz="";
var Pi=pi;
var H=1.0079;
var He=4.0026;
var Li=6.941;
var Be=9.0122;
var B=10.811;
var C=12.011;
var N=14.007;
var O=15.999;
var F=18.998;
var Ne=20.18;
var Na=22.99;
var Mg=24.305;
var Al=26.982;
var Si=28.086;
var P=30.974;
var S=32.065;
var Cl=35.453;
var Ar=39.948;
var K=39.098;
var Ca=40.078;
var Sc=44.956;
var Ti=47.867;
var V=50.942;
var Cr=51.996;
var Mn=54.938;
var Fe=55.845;
var Co=58.933;
var Ni=58.693;
var Cu=63.546;
var Zn=65.409;
var Ga=69.723;
var Ge=72.64;
var As=74.922;
var Se=78.96;
var Br=79.904;
var Kr=83.798;
var Rb=85.468;
var Sr=87.62;
var Y=88.906;
var Zr=91.224;
var Nb=92.906;
var Mo=95.94;
var Tc=98;
var Ru=101.07;
var Rh=102.91;
var Pd=106.42;
var Ag=107.87;
var Cd=112.41;
var In=114.82;
var Sn=118.71;
var Sb=121.76;
var Te=127.6;
var I=126.9;
var Xe=131.29;
var Cs=132.91;
var Ba=137.33;
var La=138.91;
var Ce=140.12;
var Pr=140.91;
var Nd=144.24;
var Pm=145;
var Sm=150.36;
var Eu=151.96;
var Gd=157.25;
var Tb=158.93;
var Dy=162.5;
var Ho=164.93;
var Er=167.26;
var Tm=168.93;
var Yb=173.04;
var Lu=174.97;
var Hf=178.49;
var Ta=180.95;
var W=183.84;
var Re=186.21;
var Os=190.23;
var Ir=192.22;
var Pt=195.08;
var Au=196.97;
var Hg=200.59;
var Tl=204.38;
var Pb=207.2;
var Bi=208.98;
var Po=209;
var At=210;
var Rn=222;
var Fr=223;
var Ra=226;
var Ac=227;
var Th=232.04;
var Pa=231.04;
var U=238.03;
var Np=237;
var Pu=244;
var Am=243;
var Cm=247;
var Bk=247;
var Cf=251;
var Es=252;
var Fm=257;
var Md=258;
var No=259;
var Lr=262;
var Rf=267;
var Db=268;
var Sg=271;
var Bh=272;
var Hs=277;
var Mt=276;
var Ds=281;
var Rg=280;
for (var i=0; i<atom.length; i++) {
mm = atom.charAt(i);
mmup = atom.charAt(i+1);
bigup = mm.toUpperCase();
mmdn = atom.charAt(i-1);
if (mm == "[") {mm = "("}
else if (mm == "]") {mm = ")"}
else if (mm == ",") {mm = "."}
if (slovo(mm)) {atominfo = true}
if (matoperator(mm)) {atominfo = false; znak=""}
if (atominfo) {
if (matoperator(mmup)) {znak=")"}
if (matoperator(mmdn)) {izraz += "(" + mm + znak}
else if (mmdn=="(") {izraz += mm + znak}
else if (mmdn=="[") {izraz += mm + znak}
else if (slovo(mm)) {izraz += "+" + mm + znak}
else if (BrojAtoma(mmdn)) {izraz += mm + znak}
else if (BrojAtoma(mm)) {izraz += "*" + mm + znak}
else {izraz += mm + znak}
}
else {izraz += mm}
}
odgovor = eval(izraz);
return odgovor;
}
}
function slovo(znak) {
var slovo="(ABCDEFGHIKLMNOPRSTUVWXYZ";
for (var i=0; i<slovo.length; i++)
if (znak == slovo.charAt(i)) {return true} {return false}
}
function velikoslovo(znak) {
var slovo="ABCDEFGHIKLMNOPRSTUVWXYZ";
for (var i=0; i<slovo.length; i++)
if (znak == slovo.charAt(i)) {return true} {return false}
}
function maloslovo(znak) {
var slovo="abcdefghiklmnoprstuvwxyz";
for (var i=0; i<slovo.length; i++)
if (znak == slovo.charAt(i)) {return true} {return false}
}
function matoperator(znak) {
var matoperator="*/+-";
for (var i=0; i<matoperator.length; i++)
if (znak == matoperator.charAt(i)) {return true}
if (znak == "") {return true}
if (znak == null) {return true}
return false
}
function operator(znak) {
var matoperator="^*/+-";
if (matoperator.indexOf(znak) >= 0) {return true} {return false}
}
function ubacirezultat(znak) {
var ubacirezultat="^*/+";
for (var i=0; i<ubacirezultat.length; i++)
if (znak == ubacirezultat.charAt(i)) {return true}
return false
}
function BrojAtoma(znak) {
var atom = "1234567890";
for (var i=0; i<atom.length; i++)
if (znak == atom.charAt(i)) {return true} {return false}
}
function kemilimat(znak) {
var atom = "rsu";
if (atom.indexOf(znak) == -1) {return true} {return false}
}
function numformat(x){
var kut = new Array("auto", "sci", "fix");
decimala = x;
var broj = document.racunalo.oldrezultat.value;
if (decimala < 13) {
document.racunalo.notes.value += "[" + kut[asf] + decimala + "]";
}
else {
decimala = 14;
document.racunalo.notes.value += "[" + kut[asf] + "]";
}
if (broj != "0" && broj != "") {
izgledbroja(broj)
}
else {
document.racunalo.notes.value += enter;
}
document.racunalo.zadatak.focus();
}
function scifix(x) {
var kut = new Array("numauto", "numsci", "numfix");
document.getElementById(kut[asf]).style.color = '#ccc';
asf = x;
var broj = document.racunalo.oldrezultat.value;
switch(x) {
case 1:
document.getElementById('numsci').style.color = '#000';
if (decimala == 14) {
document.racunalo.notes.value += "[sci]";
}
else {
document.racunalo.notes.value += "[sci" + decimala + "]";
}
break;
case 2:
document.getElementById('numfix').style.color = '#000';
document.racunalo.izaZareza.options[2].selected = true;
if (decimala == 14) {
decimala = 2;
document.racunalo.notes.value += "[fix2]";
}
else {
document.racunalo.notes.value += "[fix" + decimala + "]";
}
break;
default:
document.getElementById('numauto').style.color = '#000';
document.racunalo.izaZareza.options[14].selected = true;
document.racunalo.notes.value += "[auto]";
decimala = 14;
}
if (broj != "0" && broj != "") {izgledbroja(broj)}
document.racunalo.zadatak.focus();
}
function raddeg(x) {
var kut = new Array("numrad", "numdeg", "numgrad");
document.getElementById(kut[rdg]).style.color = "#ccc";
rdg = x;
document.getElementById(kut[x]).style.color = "#000";
document.racunalo.zadatak.focus();
}
function seplk() {
var broj = document.racunalo.oldrezultat.value;
if (document.getElementById('seplk').checked) {
document.getElementById('seplk').checked = false;
sep1000 = 0;
}
else {
document.getElementById('seplk').checked = true;
sep1000 = 1;
}
if (broj.length > 3) {izgledbroja(broj)}
}
function izgledbroja(broj) {
var nule = "000000000000000";
var minus = "";
if (broj.charAt(0) == "-") {minus = "-";}
if (asf == 2) {
if (Math.eval(broj+"*"+minus+"1-1e-"+decimala) < 0) {broj = "0"}
}
var eplace = broj.indexOf("e");
if (eplace > 0) {
var x = broj.substring(0, eplace);
var y = broj.substring(eplace);
}
else if (asf == 1) {
var x = parseFloat(broj) * 1E50;
broj = x.toString();
eplace = broj.indexOf("e");
x = broj.substring(0, eplace);
var y = broj.substring(eplace+1);
y = parseInt(y) - 50;
y = "e" + y;
}
else {
var x = broj;
var y = "";
}
var oplace = broj.indexOf(".");
broj = parseInt(x);
if (oplace == -1) {x = "0";} {x = "0" + x.substring(oplace);}
x = parseFloat(x);
with (Math) {
x = round(x * pow(10,decimala)) / pow(10,decimala);
broj = abs(broj) + x;
}
x = broj.toString();
oplace = x.indexOf(".");
//document.racunalo.notes.value += enter + "oplace_1 = " + oplace;
if (oplace == 0) {
broj = "0" + x + nule.substring(0, decimala);
}
else if (oplace > 0) {
x = x.concat(nule);
broj = x.substring(0, oplace);
broj += x.substring(oplace, oplace+decimala+1);
}
else {
broj = x + "." + nule.substring(0, decimala);
}
if (decimala == 14) {broj = parseFloat(broj)}
broj = minus.concat(broj, y);
//PROBA POCETAK
if (sep1000) {
//document.racunalo.notes.value += enter + "separator_1 = " + broj;
var rezultat = "";
var strexp = "";
oplace = broj.indexOf('.');
//if (oplace == -1) {oplace = 0;}
eplace = broj.indexOf('e');
if (eplace == -1) {eplace = broj.length;} {strexp = broj.substring(eplace);}
var tri = 0;
for (var i=oplace+1; i<eplace; i++) {
tri += 1;
if (tri == 3) {
rezultat += broj.charAt(i) + " ";
tri = 0;
}
else {
rezultat += broj.charAt(i);
}
}
rezultat += strexp
//document.racunalo.notes.value += enter + "separator_2 = " + rezultat;
if (oplace > -1) {
rezultat = "." + rezultat;
tri = 0;
for (var i=oplace-1; i>=0; i--) {
if (tri == 3) {
rezultat = broj.charAt(i) + " " + rezultat;
tri = 0;
}
else {
rezultat = broj.charAt(i) + rezultat;
}
tri += 1;
}
}
rezultat = rezultat.replace("- ", "-");
broj = rezultat;
//document.racunalo.notes.value += enter + "separator_3 = " + rezultat;
}
//PROBA KRAJ
document.racunalo.rezultat.value = broj;
document.racunalo.notes.value += " = " + broj + enter;
return broj;
}
function zaokruzi_new(ebroj) {
// max 16 decimala
//var n=16;
var x=ebroj.toExponential(decimala);
document.racunalo.notes.value += enter + "toExponential = " + x + enter;
var x=ebroj.toPrecision(decimala);
document.racunalo.notes.value += "toPrecision = " + x + enter;
var x=ebroj.toFixed(decimala);
document.racunalo.notes.value += "toFixed = " + x + enter;
document.racunalo.rezultat.value = x;
document.racunalo.notes.value += " = " + x + enter;
}
function vidi(me) {
//if (document.getElementById) {
stanje = (document.getElementById(me).style.display == 'block') ? 'none' : 'block';
document.getElementById(me).style.display = stanje;
//document.getElementById(me).style.visibility = stanje
//}
}
//Eni Generalic, Split, Create: 1999/10/14; Update: 2008/03/01
// Copyright © 2008 by EniG.
</script>
Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:
<div id="calc4chem">
<!--
/*
This script downloaded from www.JavaScriptBank.com
Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
-->
<!-- BEGIN calc4chem -->
<form action="http://www.periodni.com" name="racunalo">
<input type="hidden" name="oldrezultat" value="">
<input type="hidden" name="memorija" value="Memory recall">
<div id="kalkulator">
<div class="displej">
<input type="text" name="numauto" value="AUTO" id="numauto" onfocus="ascifix[0].click()">
<input type="text" name="numsci" value="SCI" id="numsci" onfocus="ascifix[1].click()">
<input type="text" name="numfix" value="FIX" id="numfix" onfocus="ascifix[2].click()">
<input type="text" name="nummem" value="MEM" id="nummem" onfocus="MS.click()">
<input type="text" name="numrad" value="RAD" id="numrad" onfocus="stupnjevi[0].click()">
<input type="text" name="numdeg" value="DEG" id="numdeg" onfocus="stupnjevi[1].click()">
<input type="text" name="numgrad" value="GRAD" id="numgrad" onfocus="stupnjevi[2].click()">
<input type="text" name="upit" value="Problem" onClick="this.select()" class="upit">
<input type="text" name="rezultat" value="Solution" onClick="this.select()" class="rezultat">
</div>
<div class="zadatak">
<input type="text" name="zadatak" value="" onKeyDown="if (event.keyCode==13) {enter.click()}" class="unos">
</div>
<input type="button" name="cls" value="Cls" title="Clear" onClick="memory(3)" class="cls">
<div class="tipkovnica">
<input type="button" name="sqrt" value="√¯" title="Square root" onClick="izracunaj(3)" class="b11">
<input type="button" name="root" value="y√¯x" title="Root" onClick="izracunaj(22)" class="b12">
<input type="button" name="ln" value="ln" title="Natural logarithm" onClick="izracunaj(5)" class="b13">
<input type="button" name="log" value="log" title="Common logarithm" onClick="izracunaj(8)" class="b14">
<input type="button" name="tan" value="tan" title="Tangent" onClick="izracunaj(14)" class="b15">
<input type="button" name="atan" value="atan" title="Arc tangent" onClick="izracunaj(10)" class="b16">
<input type="button" name="kvadrat" value="x²" title="Square" onClick="izracunaj(2)" class="b21">
<input type="button" name="potencija" value="x^y" title="Power" onClick="izracunaj(21)" class="b22">
<input type="button" name="aln" value="e^x" title="Natural antilogarithm" onClick="izracunaj(6)" class="b23">
<input type="button" name="alog" value="10^x" title="Common antilogarithm" onClick="izracunaj(9)" class="b24">
<input type="button" name="cos" value="cos" title="Cosine" onClick="izracunaj(15)" class="b25">
<input type="button" name="acos" value="acos" title="Arc cosine" onClick="izracunaj(11)" class="b26">
<input type="button" name="sign" value="+/-" title="Sign change" onClick="izracunaj(4)" class="b31">
<input type="button" name="1/x" value="1/x" title="Reciprocal" onClick="izracunaj(7)" class="b32">
<input type="button" name="fact" value="x!" title="Factorial" onClick="izracunaj(20)" class="b33">
<input type="button" name="postotak" value="%" title="Percent" onClick="izracunaj(17)" class="b34">
<input type="button" name="sin" value="sin" title="Sine" onClick="izracunaj(16)" class="b35">
<input type="button" name="asin" value="asin" title="Arc sine" onClick="izracunaj(12)" class="b36">
<input type="button" name="7" value="7" title="Seven" onClick="dodajBroj(7)" class="b41">
<input type="button" name="8" value="8" title="Eight" onClick="dodajBroj(8)" class="b42">
<input type="button" name="9" value="9" title="Nine" onClick="dodajBroj(9)" class="b43">
<input type="button" name="djeljeno" value="÷" title="Division" onClick="dodajBroj('/')" class="b44">
<input type="button" name="MS" value="MS" title="Memory store" onClick="memory(1)" class="b45">
<input type="button" name="MR" value="MR" title="Memory recall" onClick="memory(2)" class="b46">
<input type="button" name="4" value="4" title="Four" onClick="dodajBroj(4)" class="b51">
<input type="button" name="5" value="5" title="Five" onClick="dodajBroj(5)" class="b52">
<input type="button" name="6" value="6" title="Six" onClick="dodajBroj(6)" class="b53">
<input type="button" name="puta" value="×" title="Multiplication" onClick="dodajBroj('*')" class="b54">
<input type="button" name="con" value="Constants" title="Physical Constants" onClick="vidi('konstante'); return false;" class="b55">
<input type="button" name="1" value="1" title="One" onClick="dodajBroj(1)" class="b61">
<input type="button" name="2" value="2" title="Two" onClick="dodajBroj(2)" class="b62">
<input type="button" name="3" value="3" title="Three" onClick="dodajBroj(3)" class="b63">
<input type="button" name="minus" value="-" title="Subtraction" onClick="dodajBroj('-')" class="b64">
<input type="button" name="lijevo" value="(" title="Parentheses" onClick="dodajBroj('(')" class="b65">
<input type="button" name="desno" value=")" title="Parentheses" onClick="dodajBroj(')')" class="b66">
<input type="button" name="0" value="0" title="Zero" onClick="dodajBroj(0)" class="b71">
<input type="button" name="." value="." title="Decimal point" onClick="dodajBroj('.')" class="b72">
<input type="button" name="exp" value="exp" title="Exponent" onClick="dodajBroj('e')" class="b73">
<input type="button" name="plus" value="+" title="Addition" onClick="dodajBroj('+')" class="b74">
<input type="button" name="enter" value="=" title="Calculate" onClick="izracunaj(1)" class="b75">
</div> <!-- END tipkovnica -->
<div id="numformat">
<p class="formatnaslov">Number formats</p>
<div class="formatbr">
<div class="automatik">
<input type="radio" name="ascifix" checked title="Automatic" onClick="scifix(0)">
<a href="javascript:document.racunalo.ascifix[0].click()" onMouseOver="self.status='Automatic'; return true">Auto</a>
</div>
<div class="scienc">
<input type="radio" name="ascifix" title="Scientific notation" onClick="scifix(1)">
<a href="javascript:document.racunalo.ascifix[1].click()" onMouseOver="self.status='Scientific notation'; return true">Sci</a>
</div>
<div class="fiksed">
<input type="radio" name="ascifix" title="Fixed number of decimal places" onClick="scifix(2)">
<a href="javascript:document.racunalo.ascifix[2].click()" onMouseOver="self.status='Fixed number of decimal places'; return true">Fix</a>
</div>
<div class="decnaslov">Decimals</div>
<select name="izaZareza" SIZE="1" onChange="numformat(this.selectedIndex)" class="decimal">
<option value="0"> 0 </option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
<option value="3"> 3 </option>
<option value="4"> 4 </option>
<option value="5"> 5 </option>
<option value="6"> 6 </option>
<option value="7"> 7 </option>
<option value="8"> 8 </option>
<option value="9"> 9 </option>
<option value="10"> 10 </option>
<option value="11"> 11 </option>
<option value="12"> 12 </option>
<option value="13"> ---- </option>
<option value="14" selected> auto </option>
</select>
<div class="separator">
<a href="javascript:seplk()" onMouseOver="self.status='Separator tisu?ica'; return true">1000 separator </a>
<input type="checkbox" id="seplk" onClick="seplk()">
</div>
</div> <!-- END formatbr -->
<div class="rad">
<input type="radio" name="stupnjevi" checked title="Radians" onClick="raddeg(0)">
<span class="deg">
<a href="javascript:document.racunalo.stupnjevi[0].click()" onMouseOver="self.status='Radians'; return true">Rad </a>
</span>
<input type="radio" name="stupnjevi" title="Degrees" onClick="raddeg(1)">
<span class="deg">
<a href="javascript:document.racunalo.stupnjevi[1].click()" onMouseOver="self.status='Degrees'; return true">Deg </a>
</span>
<input type="radio" name="stupnjevi" title="Grads" onClick="raddeg(2)">
<span class="deg">
<a href="javascript:document.racunalo.stupnjevi[2].click()" onMouseOver="self.status='Grads'; return true">Grad</a>
</span>
</div>
<input type="button" name="close" value="Close" title="Close Form" onClick="memory(4)" class="n4">
<div class="n2copy">Copyright © 2008 by Eni Generalic</div>
</div> <!-- END numformat -->
</div> <!-- END racunalo -->
<div id="biljeska">
<textarea name="notes" class="tekstarea">
Calc4Chem - www.periodni.com
</textarea>
<input type="button" name="mode" value="Mode" title="Number formats" onClick="memory(4)" class="n1">
<input type="button" name="select" value="Select All" title="Select All" onClick="document.racunalo.notes.select()" class="n2">
<input type="reset" name="clear" value="Clear" title="Clear All" onClick="memory(5)" class="n3">
</div> <!-- END biljeska -->
<div id="konstante">
<div class="constnaslov"><b>PHYSICAL CONSTANTS</b></div>
<div class="const" onClick="dodajConst(-273.15)"><a href="#">Absolute zero<br>-273.15 °C</a></div>
<div class="const" onClick="dodajConst(9.80665)"><a href="#">Acceleration of free fall, standard<br>9.80665 m/s<sup>2</sup></a></div>
<div class="const" onClick="dodajConst(1.6605402e-27)"><a href="#">Atomic mass unit<br>1.6605402×10<sup>-27</sup> kg</a></div>
<div class="const" onClick="dodajConst(6.0221367e23)"><a href="#">Avogadro constant<br>6.0221367×10<sup>23</sup> 1/mol</a></div>
<div class="const" onClick="dodajConst(2.718281828)"><a href="#">Base of natural logarithms <br>2.718281828</a></div>
<div class="const" onClick="dodajConst(1.380658e-23)"><a href="#">Boltzmann constant<br>1.380658×10<sup>-23</sup> J/K</a></div>
<div class="const" onClick="dodajConst(2.81794092e-15)"><a href="#">Classical electron radius<br>2.81794092×10<sup>-15</sup> m</a></div>
<div class="const" onClick="dodajConst(9.1093897e-31)"><a href="#">Electron mass<br>9.1093897×10<sup>-31</sup> kg</a></div>
<div class="const" onClick="dodajConst(5.44617013e-4)"><a href="#">Electron-proton mass ratio<br>5.44617013×10<sup>-4</sup></a></div>
<div class="const" onClick="dodajConst(1.6021892e-19)"><a href="#">Electronvolt<br>1.6021892×10<sup>-19</sup> J</a></div>
<div class="const" onClick="dodajConst(1.60217733e-19)"><a href="#">Elementary charge<br>1.60217733×10<sup>-19</sup> C</a></div>
<div class="const" onClick="dodajConst(96485.309)"><a href="#">Faraday constant<br>96485.309 C/mol</a></div>
<div class="const" onClick="dodajConst(3.7417749e-16)"><a href="#">First radiation constant<br>3.7417749×10<sup>-16</sup> W m<sup>2</sup></a></div>
<div class="const" onClick="dodajConst(8.314510)"><a href="#">Molar gas constant<br>8.314510 J/mol K</a></div>
<div class="const" onClick="dodajConst(0.02241410)"><a href="#">Molar volume<br>(Ideal gas, <i>T</i> = 273.15 K, <i>p</i> = 101.325 kPa)<br>0.02241410 m<sup>3</sup>/mol</a></div>
<div class="const" onClick="dodajConst(6.67259e-11)"><a href="#">Newtonian constant of gravitation<br>6.67259×10<sup>-11</sup> N m<sup>2</sup>/kg<sup>2</sup></a></div>
<div class="const" onClick="dodajConst(12.566370614e-7)"><a href="#">Permeability of vacuum<br>12.566370614×10<sup>-7</sup> N/A<sup>2</sup></a></div>
<div class="const" onClick="dodajConst(8.854187817e-12)"><a href="#">Permittivity of vacuum<br>8.854187817×10<sup>-12</sup> F/m</a></div>
<div class="const" onClick="dodajConst(3.1415926535897932)"><a href="#">PI<br>3.1415926535897932</a></div>
<div class="const" onClick="dodajConst(6.6260755e-34)"><a href="#">Planck constants<br>6.6260755×10<sup>-34</sup> J s</a></div>
<div class="const" onClick="dodajConst(0.01438769)"><a href="#">Second radiation constant<br>0.01438769 m K</a></div>
<div class="const" onClick="dodajConst(1400)"><a href="#">Solar constant<br>1400 W/m<sup>2</sup></a></div>
<div class="const" onClick="dodajConst(299792458)"><a href="#">Speed of light in vacuum<br>299792458 m/s</a></div>
<div class="const" onClick="dodajConst(340)"><a href="#">Speed of sound in air at STP<br>340 m/s</a></div>
<div class="const" onClick="dodajConst(101325)"><a href="#">Standard pressure<br>101325 Pa</a></div>
</div> <!-- END konstante -->
</form>
<div class="crta"></div>
</div>
-
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: Copy & Paste JavaScript code below in your HEAD section
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: must download files below
Files
plus.png
-
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: Place JavaScript below in your HEAD section
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: 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
*/
-->
<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: downloads
Files
mootools.js
-
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: Place CSS below in your 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
-
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
-
Creative HTML5 and JavaScript Asteroid Game
Today in this post, jsB@nk want to present to you a simple JavaScript application made by HTML5; name of this web-based JavaScript g... 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">
/*
This script downloaded from www.JavaScriptBank.com
Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
* {
-webkit-touch-callout: none; /* prevent callout to copy image, etc when tap to hold */
-webkit-text-size-adjust: none; /* prevent webkit from resizing text to fit */
/* make transparent link selection, adjust last value opacity 0 to 1.0 */
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-user-select: none; /* prevent copy paste, to allow, change 'none' to 'text' */
-webkit-tap-highlight-color: rgba(0,0,0,0);
}
body {
margin: 0px;
}
canvas {
display: block;
background-color: #113;
}
</style>
Step 2: Copy & Paste JavaScript code below in your HEAD section
JavaScript
Code:
<script type="text/javascript">
/*
This script downloaded from www.JavaScriptBank.com
Come to view and download over 2000+ free javascript at www.JavaScriptBank.com
*/
var Vector2 = function (x,y) {
this.x= x || 0;
this.y = y || 0;
};
Vector2.prototype = {
reset: function ( x, y ) {
this.x = x;
this.y = y;
return this;
},
toString : function (decPlaces) {
decPlaces = decPlaces || 3;
var scalar = Math.pow(10,decPlaces);
return "[" + Math.round (this.x * scalar) / scalar + ", " + Math.round (this.y * scalar) / scalar + "]";
},
clone : function () {
return new Vector2(this.x, this.y);
},
copyTo : function (v) {
v.x = this.x;
v.y = this.y;
},
copyFrom : function (v) {
this.x = v.x;
this.y = v.y;
},
magnitude : function () {
return Math.sqrt((this.x*this.x)+(this.y*this.y));
},
magnitudeSquared : function () {
return (this.x*this.x)+(this.y*this.y);
},
normalise : function () {
var m = this.magnitude();
this.x = this.x/m;
this.y = this.y/m;
return this;
},
reverse : function () {
this.x = -this.x;
this.y = -this.y;
return this;
},
plusEq : function (v) {
this.x+=v.x;
this.y+=v.y;
return this;
},
plusNew : function (v) {
return new Vector2(this.x+v.x, this.y+v.y);
},
minusEq : function (v) {
this.x-=v.x;
this.y-=v.y;
return this;
},
minusNew : function (v) {
return new Vector2(this.x-v.x, this.y-v.y);
},
multiplyEq : function (scalar) {
this.x*=scalar;
this.y*=scalar;
return this;
},
multiplyNew : function (scalar) {
var returnvec = this.clone();
return returnvec.multiplyEq(scalar);
},
divideEq : function (scalar) {
this.x/=scalar;
this.y/=scalar;
return this;
},
divideNew : function (scalar) {
var returnvec = this.clone();
return returnvec.divideEq(scalar);
},
dot : function (v) {
return (this.x * v.x) + (this.y * v.y) ;
},
angle : function (useRadians) {
return Math.atan2(this.y,this.x) * (useRadians ? 1 : Vector2Const.TO_DEGREES);
},
rotate : function (angle, useRadians) {
var cosRY = Math.cos(angle * (useRadians ? 1 : Vector2Const.TO_RADIANS));
var sinRY = Math.sin(angle * (useRadians ? 1 : Vector2Const.TO_RADIANS));
Vector2Const.temp.copyFrom(this);
this.x= (Vector2Const.temp.x*cosRY)-(Vector2Const.temp.y*sinRY);
this.y= (Vector2Const.temp.x*sinRY)+(Vector2Const.temp.y*cosRY);
return this;
},
equals : function (v) {
return((this.x==v.x)&&(this.y==v.x));
},
isCloseTo : function (v, tolerance) {
if(this.equals(v)) return true;
Vector2Const.temp.copyFrom(this);
Vector2Const.temp.minusEq(v);
return(Vector2Const.temp.magnitudeSquared() < tolerance*tolerance);
},
rotateAroundPoint : function (point, angle, useRadians) {
Vector2Const.temp.copyFrom(this);
//trace("rotate around point "+t+" "+point+" " +angle);
Vector2Const.temp.minusEq(point);
//trace("after subtract "+t);
Vector2Const.temp.rotate(angle, useRadians);
//trace("after rotate "+t);
Vector2Const.temp.plusEq(point);
//trace("after add "+t);
this.copyFrom(Vector2Const.temp);
},
isMagLessThan : function (distance) {
return(this.magnitudeSquared()<distance*distance);
},
isMagGreaterThan : function (distance) {
return(this.magnitudeSquared()>distance*distance);
}
// still AS3 to convert :
// public function projectOnto(v:Vector2) : Vector2
// {
// var dp:Number = dot(v);
//
// var f:Number = dp / ( v.x*v.x + v.y*v.y );
//
// return new Vector2( f*v.x , f*v.y);
// }
//
//
// public function convertToNormal():void
// {
// var tempx:Number = x;
// x = -y;
// y = tempx;
//
//
// }
// public function getNormal():Vector2
// {
//
// return new Vector2(-y,x);
//
// }
//
//
//
// public function getClosestPointOnLine ( vectorposition : Point, targetpoint : Point ) : Point
// {
// var m1 : Number = y / x ;
// var m2 : Number = x / -y ;
//
// var b1 : Number = vectorposition.y - ( m1 * vectorposition.x ) ;
// var b2 : Number = targetpoint.y - ( m2 * targetpoint.x ) ;
//
// var cx : Number = ( b2 - b1 ) / ( m1 - m2 ) ;
// var cy : Number = m1 * cx + b1 ;
//
// return new Point ( cx, cy ) ;
// }
//
};
Vector2Const = {
TO_DEGREES : 180 / Math.PI,
TO_RADIANS : Math.PI / 180,
temp : new Vector2()
};
(function () {
var spareBullets = [];
window.Bullet = function (ctx, x, y, angle) {
// this is rather nasty - so I'm not sure why I'm doing it...
if (this === window) {
if (spareBullets.length) {
var bullet = spareBullets.pop();
bullet.init(x, y, angle);
bullet.fresh = false;
return bullet;
} else {
return new Bullet(ctx, x, y, angle);
}
}
this.ctx = ctx;
// initialise
this.init(x, y, angle);
return this;
};
Bullet.prototype = {
init: function (x, y, angle) {
this.fresh = true;
this.pos = new Vector2(x,y);
this.vel = new Vector2(Bullet.speed,0);
this.vel.rotate(angle);
this.enabled = true;
// 15 is the length of the ship
this.pos.plusEq(this.vel.clone().normalise().multiplyEq(15));
},
checkEnabled: function () {
var ctx = this.ctx;
if (this.enabled == false) {
return;
}
if (this.pos.x < 0 || this.pos.x > ctx.canvas.width) this.enabled = false;
if (this.pos.y < 0 || this.pos.y > ctx.canvas.height) this.enabled = false;
if (this.enabled == false) {
spareBullets.push(this);
}
},
update: function () {
this.pos.plusEq(this.vel);
this.checkEnabled();
return this;
},
draw: function () {
var ctx = this.ctx,
pos = this.pos;
ctx.save();
ctx.lineWidth = 2;
ctx.strokeStyle = "#fff";
ctx.beginPath();
ctx.arc(pos.x, pos.y, 2, 0, Math.PI*2, true);
ctx.stroke();
ctx.restore();
return this;
}
};
// static
Bullet.speed = 5;
})();
Asteroid = function (x,y,radius)
{
this.pos = new Vector2(x,y);
this.vel = new Vector2(0,0);
this.points;
this.enabled = true;
// temp vector to calculate distance from circle in hitTest
this.diff = new Vector2(0,0);
this.reset = function (radius) {
this.points = [];
this.radius = radius;
var temp = new Vector2(radius, 0);
for (var angle = 0; angle<360; angle+= random(0, 45)) {
temp.reset(random(radius / 2, radius),0);
temp.rotate(angle);
this.points.push(temp.clone());
}
};
this.reset(radius);
this.update = function(canvas) {
this.pos.plusEq(this.vel);
if(this.pos.x+this.radius < 0) this.pos.x = canvas.width+this.radius;
else if (this.pos.x-this.radius > canvas.width) this.pos.x = -this.radius;
if(this.pos.y+this.radius < 0) this.pos.y = canvas.height+this.radius;
else if (this.pos.y-this.radius > canvas.height) this.pos.y = -this.radius;
};
this.draw = function(ctx) {
ctx.save();
ctx.translate(this.pos.x, this.pos.y);
ctx.strokeStyle = "#fff";
ctx.fillStyle = '#000';
ctx.lineWidth = 2;
ctx.beginPath();
for(var i = 0; i<this.points.length; i++) {
var p = this.points[i % this.points.length];
ctx.lineTo(p.x, p.y);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
};
this.hitTest = function(x,y) {
this.diff.copyFrom(this.pos);
this.diff.x-=x;
this.diff.y-=y;
var distanceSq = (this.diff.x * this.diff.x) + (this.diff.y*this.diff.y);
return distanceSq < (this.radius * this.radius);
};
};
ShipMoving = function(x,y) {
this.pos = new Vector2(x,y);
this.angle = 0;
this.vel = new Vector2(0,0);
this.temp = new Vector2(0,0);
this.thrustPower = 0.1;
this.rotateSpeed = 5;
this.thrusting = false;
this.invulnerable = false;
this.thrustAmount = 0;
this.dead = [];
this.update = function() {
this.pos.plusEq(this.vel);
};
this.thrust = function() {
this.temp.reset(this.thrustPower,0);
this.temp.rotate(this.angle);
this.vel.plusEq(this.temp);
};
this.rotateLeft = function() {
this.angle -= this.rotateSpeed;
};
this.rotateRight = function() {
this.angle += this.rotateSpeed;
};
this.hit = function () {
var n = 20;
while (n--) {
this.dead.push(new Vector2(random(3, 6), 0));
this.dead[this.dead.length - 1].rotate(Math.random() * Math.PI * 2, true);
}
};
this.isdead = function () {
return !!this.dead.length;
};
this.draw = function(c) {
c.save();
c.translate(this.pos.x, this.pos.y);
c.rotate(this.angle * Vector2Const.TO_RADIANS);
if (this.invulnerable == false && !this.isdead()) {
c.lineWidth = 4;
if (this.thrustAmount) {
c.beginPath();
c.moveTo(-11, -3);
c.lineTo(-11, 3);
c.lineTo(-12 -this.thrustAmount, 0);
c.closePath();
c.fillStyle = 'hsla(3, 100%, 50%, 0.9)';
c.fill();
c.strokeStyle = 'hsla(32, 100%, 50%, 0.7)';
c.stroke();
}
c.lineWidth = 2;
c.strokeStyle = "#fff";
c.beginPath();
c.moveTo(-10, -10);
c.lineTo(-10, 10);
c.lineTo(14, 0);
c.closePath();
c.stroke();
} else if (this.dead.length) {
var i = this.dead.length;
c.lineWidth = 2;
c.fillStyle = 'hsla(1, 100%, 50%, 0.75)';
while (i--) {
this.dead[i].multiplyEq(1.05);
c.beginPath();
c.arc(this.dead[i].x, this.dead[i].y, 2, 0, Math.PI * 2, true);
c.closePath();
c.fill();
}
}
if (this.thrusting && this.thrustAmount < 10) {
this.thrustAmount++;
} else if (this.thrustAmount > 0) {
this.thrustAmount--;
}
c.restore();
};
};
// canvas element and 2D context
var canvas = document.createElement('canvas'),
c = canvas.getContext('2d'),
touch = 'createTouch' in document;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
document.body.appendChild(canvas);
c.strokeStyle = "#ffffff";
var mouseX, mouseY,
halfWidth = canvas.width/2,
halfHeight = canvas.height/2,
bullets = [],
spareAsteroids = [],
ship = new ShipMoving(halfWidth, halfHeight),
thrusting = false,
rotateLeft = false,
rotateRight = false,
grad = c.createLinearGradient(0, 0, 0, canvas.height),
asteroids = [],
trail = 0.85;
grad.addColorStop(0, 'hsla(240,80%,2%,' + trail + ')');
grad.addColorStop(1, 'hsla(240,100%,15%,' + trail + ')');
timer = setInterval(draw, 1000/35);
for (var i = 0; i < (touch ? 5 : 10); i++) {
asteroids.push(new Asteroid(random(0, canvas.width), random(0, canvas.height), 50));
asteroids[i].vel.reset(1,0).rotate(random(0,360));
}
function draw() {
c.fillStyle = '#000'; //grad;
c.fillRect(0,0,canvas.width, canvas.height);
var bullet;
for (var i=0; i<bullets.length; i++) {
bullet = bullets[i];
if (bullet.enabled) {
bullet.update();
bullet.draw();
}
}
for (i = 0; i < asteroids.length; i++) {
var asteroid = asteroids[i],
hit = false;
if (!ship.invulnerable && !ship.isdead() && asteroid.hitTest(ship.pos.x, ship.pos.y)) {
// you lose!
ship.hit();
}
if(!asteroid.enabled) continue;
if (!ship.isdead()) {
for (var j = 0; j < bullets.length; j++) {
if (bullets[j].enabled) {
hit = asteroid.hitTest(bullets[j].pos.x, bullets[j].pos.y);
if (hit) {
bullets[j].enabled = false;
break;
}
}
}
}
if (hit) {
if (asteroid.radius < 15) {
asteroid.enabled = false;
} else {
asteroid.reset(asteroid.radius/2);
asteroid.vel.reset(random(-5,5),random(-5,5));
makeNewAsteroid(asteroid.pos.x, asteroid.pos.y, asteroid.radius).vel.reset(random(-5,5),random(-5,5));
makeNewAsteroid(asteroid.pos.x, asteroid.pos.y, asteroid.radius).vel.reset(random(-5,5),random(-5,5));
}
} else {
asteroid.update(canvas);
asteroid.draw(c);
}
}
if (ship.thrusting) ship.thrust();
if (rotateLeft) ship.rotateLeft();
if (rotateRight) ship.rotateRight();
ship.update();
if (ship.pos.x<0) ship.pos.x = canvas.width;
else if (ship.pos.x>canvas.width) ship.pos.x = 0;
if (ship.pos.y<0) ship.pos.y = canvas.height;
else if (ship.pos.y>canvas.height) ship.pos.y = 0;
ship.draw(c);
}
function makeNewAsteroid(x, y, radius) {
var newasteroid;
if (spareAsteroids.length > 0) {
newasteroid = spareAsteroids.pop();
newasteroid.pos.set(x, y);
newasteroid.radius = radius;
} else {
newasteroid = new Asteroid(x, y, radius);
asteroids.push(newasteroid);
}
return newasteroid;
}
function fire() {
if (ship.isdead()) {
return;
}
// only allow n bullets
var limit = 5,
i = bullets.length;
while (i--) {
if (bullets[i].enabled) {
limit--;
}
}
if (limit !== 0) {
var bullet = Bullet(c, ship.pos.x, ship.pos.y, ship.angle);
if (bullet.fresh) bullets.push(bullet);
}
}
canvas.addEventListener( 'mousemove', onMouseMove, false );
document.addEventListener( 'keydown', onKeyDown, false );
document.addEventListener( 'keyup', onKeyUp, false );
document.addEventListener( 'touchstart', onTouchStart, false );
document.addEventListener( 'touchmove', onTouchMove, false );
document.addEventListener( 'touchend', onTouchEnd, false );
var swipe = [];
if (touch) {
ship.thrustPower = 0.5;
}
function onTouchStart(e) {
swipe = [];
if (e.touches.length == 1) {
// rotate & fire
var v = new Vector2(e.touches[0].pageX-canvas.width/2, e.touches[0].pageY-canvas.height/2);
ship.angle = v.angle();
fire();
} else if (e.touches.length == 2) {
ship.thrusting = true;
ship.thrust();
} else if (e.touches.length == 3) {
ship.invulnerable = true;
}
}
function onTouchMove(e) {
e.preventDefault();
}
// window.addEventListener('devicemotion', function(event) {
// var v = new Vector2(event.accelerationIncludingGravity.x, event.accelerationIncludingGravity.y);
// ship.angle += v.angle() * 0.05;
// }, false);
function onTouchEnd(e) {
ship.thrusting = false;
ship.invulnerable = false;
}
function onKeyDown(e) {
if(e.keyCode == 38) ship.thrusting = true;
else if (e.keyCode == 40) ship.invulnerable = true;
else if(e.keyCode == 37) rotateLeft = true;
else if (e.keyCode == 39) rotateRight = true;
else if (e.which == 32) fire();
}
function onKeyUp(e) {
if (e.keyCode == 38) ship.thrusting = false;
else if (e.keyCode == 40) ship.invulnerable = false;
else if(e.keyCode == 37) rotateLeft = false;
else if (e.keyCode == 39) rotateRight = false;
}
function onMouseMove(event) {
mouseX = event.offsetX;
mouseY = event.offsetY;
}
function random(v1, v2){
return ((Math.random()*(v2-v1))+v1);
}
setTimeout(function () {
window.scrollTo(1, 0);
}, 1000);
</script>
Step 3: Copy & Paste HTML code below in your BODY section
HTML
Code:
<canvas height="609" width="1139"></canvas>
Step 4: Download files below
Files
demo.html
-
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
-
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: 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
*/
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: Copy & Paste JavaScript code 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