|
Scripts and Tools Share your free scripts , tools , icons, fontz, screen savers , etc here. |
|
Thread Tools | Display Modes |
#171
|
|||
|
|||
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... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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 */ .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> 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> 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> |
#172
|
|||
|
|||
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.... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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> HTML Code:
$ <input type="text" name="currencyField1" onchange="currency(this);" /> |
#173
|
|||
|
|||
Awesome Tabbing Navigation with Prototype and AJAX
A very cool [Only Registered users can see links . Click Here To Register...] to create tabbing navigation menus for display information on your web pages. This tabb... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] How to setup Step 1: Download files below Files [Only Registered users can see links . Click Here To Register...] |
#174
|
|||
|
|||
XMLWriter: Simple JavaScript XML Creator
[Only Registered users can see links . Click Here To Register...] - a type of data defining - becoming more popular at present because of its flexibility and convenience, data defined by XML become more visual and... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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> 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> |
#175
|
|||
|
|||
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... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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 */ 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> 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> 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> |
#176
|
|||
|
|||
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.
... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...] [Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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 */ 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> 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> 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> |
#177
|
|||
|
|||
Cool Analog Clock with Raphael by Amazing Styles
Collect the [Only Registered users can see links . Click Here To Register...] for creating cool JavaScript clocks is one of jsB@nk's initial criteria; till to this... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] How to setup Step 1: downloads Files [Only Registered users can see links . Click Here To Register...] |
#178
|
|||
|
|||
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 [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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> 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> 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> |
#179
|
|||
|
|||
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:
- [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...] [Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] How to setup Step 1: Place JavaScript below in your HEAD section 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> 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> |
#180
|
|||
|
|||
Nice AJAX Effects for Messages Box using MooTools
This is very simple [Only Registered users can see links . Click Here To Register...] but it can create an amazing message box effect with AJAX operations, bases on ... [Only Registered users can see links . Click Here To Register...] at [Only Registered users can see links . Click Here To Register...]
[Only Registered users can see links . Click Here To Register...] Demo: [Only Registered users can see links . Click Here To Register...] 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> 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> HTML Code:
Press "Save"</p> <div id="box"></div> <input name="" type="text" /><input id="save_button" name="save_button" type="button" value="save"/> Files [Only Registered users can see links . Click Here To Register...] |
Bookmarks |
|
|