JavaScript - Javascript Code Optimization
Hey guys, I'm new both to this forum and javascript, I have made this small game to get me used to the canvas element, and basically just to entertain myself.
http://beta.amando-filipe.co.cc/pong.html Right, take a look at the source code, I had to make that big Start() function so it would work on firefox, I am used to google chrome and apparently even badly made javascript runs on it, so I had to do a quick fix for firefox, what is the other way? Apparently I can't call functions inside the start function with events, like onmousedown etc. Here is the lates code, not yet uploaded to the site: Code: <!DOCTYPE html> <html> <head> <link rel="shortcut icon" href="http://i.imgur.com/N7PTg.png"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <title>canvasPong</title> <style type='text/css'> body{background-color:#333; text-align:center;} #text{width:750px;text-align:left;margin:0 auto;color:#FFF;} .painted{background-color:#222;border-ballRadius:5px; -moz-border-ballRadius:5px; padding:5px; margin: 5px;} iframe{background-color:#999;padding:5px;border-ballRadius:5px; -moz-border-ballRadius:5px;} </style> <script type='text/javascript'> var ballSpeedX = 1; var ballSpeedY = 1; //5 var pause = false; var lost = false; var pts = 0; timer = false; var time = 0; var scoreset = false; function Start() { /* System variables */ var frameDelay = 20; var players = document.getElementById('players'); var playerInfo = players.getContext('2d'); var screen = document.getElementById('screen'); // Set up animation screen var ctx = screen.getContext('2d'); // Set up animation screen var out = document.getElementById('out'); // Set up information screen var writeTo = out.getContext('2d'); // Set up information screen var WIDTH = document.getElementById('screen').width; var HEIGHT = document.getElementById('screen').height; var WWIDTH = document.getElementById('out').width; var WHEIGHT = document.getElementById('out').height; /* END */ /* Coordinate variables */ /* Colour related variables */ var R = 0; var G = 0; var B = 0; /* end */ /* Object variables */ var ballRadius = 10; var ballX = ballRadius + 2; var ballY = ballRadius + 2; /* end */ var lap = 0; /* end */ var paddleY = 0; var prevPadY = 0; var paddleWidth = 10; var paddleHeight = 60; var padDistToWall = 5; var paddleX = WIDTH - padDistToWall - paddleWidth; var mousemoved = false; var speed; var key = 0; var highScores = [0, 0, 0, 0, 0]; highScores.length = 5; var usr = ["", "", "", "", ""]; usr.length = 5; var pify = 8; var playerY = 20; function bounce() { if (pts >= 10) { lost = true; } if (lost === true) { frameDelay = 10000; paddleY += 0; ballSpeedX += 0; ballSpeedY += 0; writeCtx("You lost", 200, 150, 'purple', 50); writeCtx("Press space bar to start new game", 180, 210, 'purple', 15); if (scoreset === false) { checkScore(); } } else if (pause === true) { frameDelay = 10000; ballSpeedX += 0; ballSpeedY += 0; paddleY += 0; writeCtx("Paused", 200, 150, 'purple', 50); writeCtx("Press space bar to resume", 195, 210, 'purple', 15); } else { ballX += ballSpeedX; ballY += ballSpeedY; if (ballX - ballRadius <= 0) { ballSpeedX *= -1; } else { ballSpeedX *= 1; } if (ballY + ballRadius >= HEIGHT || ballY - ballRadius <= 0) { ballSpeedY *= -1; } else { ballSpeedY *= 1; } if (ballY >= paddleY && ballY <= paddleY + paddleHeight && ballX + ballRadius > paddleX && ballX - ballRadius < paddleX + paddleWidth) { // Hits paddle horizontally if (speed >= 30) { ballSpeedX += 0; ballSpeedY += 0; } else { ballSpeedX += Math.random(); ballSpeedY += Math.random() + 0.2; } ballSpeedX *= -1; R = randomNum(100, 255); G = randomNum(100, 255); } if(ballX >= paddleX && ballX <= paddleX + paddleWidth && ballY + ballRadius > paddleY && ballY - ballRadius < paddleY + paddleHeight){ ballSpeedY *= -1; } if (ballX + ballRadius >= WIDTH) { pts += 1; ballX = 20; ballY = randomNum(20, 380); writeCtx("OOOPS!", 200, 150, 'purple', 50); } } } function randomNum(min, max) { var Xz = Math.random() * max; while (Xz < min) { Xz = Math.random() * max; } return Math.round(Xz); } function paddle() { ctx.beginPath(); ctx.fillStyle = '#00CD00'; if (paddleY === undefined) { paddleY = 0; } if (paddleY + paddleHeight >= HEIGHT) { paddleY = HEIGHT - paddleHeight; } if (paddleY < 0) { paddleY = 0; } ctx.fillRect(paddleX, paddleY, paddleWidth, paddleHeight); } function rect(x, y, w, h) { ctx.beginPath(); ctx.rect(x, y, w, h); ctx.fill(); } function write(what, whereX, whereY, colour, size) { writeTo.textBaseline = 'top'; writeTo.fillStyle = colour; writeTo.font = "bold " + size + "px sans-serif"; writeTo.fillText(what, whereX, whereY); } function writeCtx(whatt, whereXt, whereYt, colourt, sizet) { ctx.textBaseline = 'top'; ctx.fillStyle = colourt; ctx.font = "bold " + sizet + "px sans-serif"; ctx.fillText(whatt, whereXt, whereYt); } function writePlayerInfo(whatz, whereXz, whereYz, colourz, sizez) { playerInfo.textBaseline = 'top'; playerInfo.fillStyle = colourz; playerInfo.font = "bold " + sizez + "px sans-serif"; playerInfo.fillText(whatz, whereXz, whereYz); } function clear() { ctx.clearRect(0, 0, WIDTH, HEIGHT); writeTo.clearRect(0, 0, WWIDTH, WHEIGHT); playerInfo.clearRect(0, 0, WWIDTH, WHEIGHT); } function round(x, y, rad, shape, colour) { ballRadius = rad; ctx.beginPath(); ctx.fillStyle = colour; ctx.arc(x, y, rad, 0, Math.PI * 180, false); ctx.fill(); } function delay(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while (curDate - date < millis); } function checkScore() { if ((time / 1000) > highScores[0] && (time / 1000) > highScores[1]) { scoreset = true; for (n = highScores.length; n > 0; n--) { highScores[n] = highScores[n - 1]; // Scroll down. usr[n] = usr[n - 1]; } highScores[0] = (time / 1000); usr[0] = prompt("You have set a new record, insert a nickname to save your score", ""); } else if ((time / 1000) > highScores[1] && (time / 1000) > highScores[2]) { scoreset = true; for (n = highScores.length; n > 1; n--) { highScores[n] = highScores[n - 1]; // Scroll down. usr[n] = usr[n - 1]; } highScores[1] = time / 1000; usr[1] = prompt("You have set a new record, insert a nickname to save your score", ""); } else if ((time / 1000) > highScores[2] && (time / 1000) > highScores[3]) { scoreset = true; for (n = highScores.length; n > 2; n--) { highScores[n] = highScores[n - 1]; // Scroll down. usr[n] = usr[n - 1]; } highScores[2] = time / 1000; usr[2] = prompt("You have set a new record, insert a nickname to save your score", ""); } else if ((time / 1000) > highScores[3] && (time / 1000) > highScores[4]) { scoreset = true; for (n = highScores.length; n > 3; n--) { highScores[n] = highScores[n - 1]; // Scroll down. usr[n] = usr[n - 1]; } highScores[3] = time / 1000; usr[3] = prompt("You have set a new record, insert a nickname to save your score", ""); } else if ((time / 1000) > highScores[4]) { scoreset = true; for (n = highScores.length; n > 4; n--) { highScores[n] = highScores[n - 1]; // Scroll down. usr[n] = usr[n - 1]; } highScores[4] = time / 1000; usr[4] = prompt("You have set a new record, insert a nickname to save your score", ""); } } function draw() { clear(); round(ballX, ballY , ballRadius, 0, 'rgb(' + R + ',' + G + ',' + B + ')'); write('Ball X: ' + Math.round(ballX) + 'px', 2, 2, 'white', 12); write('Ball Y: ' + Math.round(ballY) + 'px', 2, 14, 'white', 12); write("pad height: " + Math.round(paddleY) + 'px', 2, 26, 'white', 12); write('Balls lost: ' + pts + "/10", 2, 38, 'white', 12); write("ball speed: " + (speed * 100) + "px/s", 2, 50, 'white', 12); write("time: " + time / 1000 + "s", 2, 62, 'white', 12); writePlayerInfo('Highscores', 29, 4, 'white', 16); playerY = 20; for (u = 0; u < highScores.length; u++) { if (highScores[u] !== 0) { writePlayerInfo(usr[u] + ", " + highScores[u] + 's', 8, playerY, 'white', 12); playerY += 12; } } speed = Math.round(Math.abs(Math.sqrt(ballSpeedX * ballSpeedX + ballSpeedY * ballSpeedY))); if (mousemoved === false) { writeCtx("Hello there, the computer is now controlling the paddle.", 10, 50, 'red', 22); writeCtx("Move the mouse over the paddle to start playing.", 40, 80, 'red', 22); writeCtx("Speed increases whenever the ball touches the paddle.", 10, 110, 'red', 22); writeCtx("Use the space bar to pause.", 120, 140, 'red', 22); paddleY = ballY ; paddleY -= paddleHeight / 2; } paddle(); bounce(); } function init() { // Set up stuff draw(); return setInterval(draw, frameDelay); } function setStuff(e) { timer = true; mousemoved = true; if (pause === true || lost === true) { paddleY = paddleY; } else { prevPadY = paddleY; paddleY = e.pageY - screen.offsetTop - 10 - (paddleHeight / 2); } } function count() { if (timer === true && lost === true) { time += 0; } else if (timer === true && pause === false && lost === false) { time += 100; } } init(); setInterval(count, 100); screen.addEventListener('mousemove', setStuff, true); } function checkKey(event) { key = event.keyCode; if (key == 32 && lost === true) { ballSpeedX = 5; ballSpeedY = 5; time = 0; pts = 0; lost = false; scoreset = false; } else if (key == 32 && pause === false) { pause = true; } else if (key == 32 && pause === true) { pause = false; } } function show_hide(what) { var object = document.getElementById(what); if (object.style.display == 'none') { object.style.display = 'block'; } else { object.style.display = 'none'; } } //]]> </script> </head> <body> <body onload="Start()" onkeydown="checkKey(event);"> <div id="text">canvasPong is the classic pong game done with the HTML5 canvas element.<br/> You can only lose 10 balls, the person that lasts the longest time wins!<br/><br/> <div class="painted" onclick="show_hide('brow');">Browser compatibility(click to show/hide):</div> <ul id="brow" style="display:none"> <li>Google chrome: Good.</li> <li>Safari: Works.</li> <li>Firefox v3.5 and over: Laggy.</li> <li>Untested but likely to work on: Opera and IE9+.</li><br/> </ul> <div class="painted" onclick="show_hide('bug');">Bugs and things to be fixed(click to show/hide):</div> <ul id="bug" style="display:none;"> <li>Only your score is stored, working on saving ALL scores.</li> <li>Sometimes the ball goes mad when it touches the paddle</li> <li>"OOPS" is too fast</li> <li>Ball physics could be better, I hate maths.</li> </ul> Coded by Amando Abreu<br/> Last edited: 30/12/2010, 01:00</div> <canvas id="players" width="150" height="400" style="border:2px solid blue;"></canvas> <canvas id="screen" width="600" height="400" style="border:2px solid blue;"></canvas> <canvas id="out" width="150" height="400" style="border:2px solid blue;"></canvas> <br/> <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fbeta.amando-filipe.co.cc%2Fpong.html&layout=standard&show_faces=false&width=450&action=like&font=arial&colorscheme=light&height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:35px;" allowTransparency="true"></iframe> </body> </html> What else could be optimized for optimal performance? thanks a lot. Similar Tutorialsi am building a graphing calculator, it works but it is slow. graph.graph(equ) is the main function it graphs. i think that this is the problomatic area. Code: var initgraph = function( canvasid ) { var graph = { } ; graph.logmsg = []; var dlog; graph.curlog = ( document.getElementById( "dlog" ) ) ? document.getElementById( "dlog" ) : null; if ( graph.curlog === null ){ graph.dlog = function() { } ; } else{ graph.dlog = dlog = function( str ) { graph.logmsg.push( str ); var temp = graph.logmsg.join( "\n" ); graph.curlog.value = temp; return str; } ; } //alert( 'debbuging log initalized' ); graph.canvas = document.getElementById( canvasid ); graph.dlog( "canvas found" ); graph.dlog( "width: " + ( graph.w = parseInt( document.defaultView.getComputedStyle( graph.canvas, null ).width, 10 ) ) ); graph.dlog( "height: " + ( graph.h = parseInt( document.defaultView.getComputedStyle( graph.canvas, null ).height, 10 ) ) ); graph.h2 = Math.round( graph.h / 2 ); graph.w2 = Math.round( graph.w / 2 ); graph.dlog( "computed styles calculated" ); graph.ctx = graph.canvas.getContext( "2d" ); graph.dlog( 'canvas context gained' ); graph.ctx.fillStyle = "#E0FFFF"; graph.dlog( 'styles set' ); graph.ctx.translate( graph.w2, graph.h2 ); graph.ctx.stroke(); graph.ctx.save(); graph.dlog( 'canvas context saved' ); graph.ctx.beginPath(); graph.dlog( 'axis postitions have been calculated' ); graph.lg = []; graph.gs = []; graph.dlog( 'arrays initialized' ); graph.goodsize = 1; if( graph.h < 200 || graph.w < 200 ){ alert( "Canvas for graph is too small.\n Minimum recomended size is 200 X 200, recomended size is 500 X 500.\nSize is " + graph.h + " X " + graph.w + ".\n Graphs may be hard to see or they may be pointless." ); graph.goodsize = 0; } else{ graph.dlog( "graph is big enuf" ); } if( graph.h != graph.w ){ alert( "The canvas is not square. Graph may not look right." ); graph.goodsize = 0; } else{ graph.dlog( 'graph is square' ); } graph.lineTo = function( x, y ){ graph.ctx.lineTo( x, - y ); return graph; } ; graph.moveTo = function( x, y ){ graph.ctx.moveTo( x, - y ); return graph; } ; graph.dot = function( xx, yy ) { if( ( typeof xx !== "number" || typeof yy !== "number" ) || Math.abs( xx ) > graph.w2 || Math.abs( yy ) > graph.h2 ) { graph.dlog( "Dot (" + xx + ", " + yy + ") will not fit on the graph. Will not attempt to graph." ); return graph; } graph.ctx.fillStyle='#2B167B'; yy = 0 - Math.round( yy ); xx = Math.round( xx ); graph.ctx.fillRect( xx - 1, yy + 1, 3, 3 ); return graph; } ; graph.dlog( 'basic graphing methods created' ); graph.da = function( axes,ticks,orgin )///////////////////////////////////////////////////////////////////////////////////////// { // if ( clr === true ) // { // graph.ctx.clearRect( - graph.w2, - graph.h2, graph.h, graph.w ); // } // old stuf. graph.ctx.strokeStyle = "#2B167B"; if( axes ){ graph.moveTo( - graph.w2, 0 ); graph.lineTo( graph.w2, 0 ); graph.moveTo( 0, - graph.h2 ); graph.lineTo( 0, graph.h2 ); //alert('axes') } if( ticks ){ var j = - 3; var i = - graph.w2; for( i; i <= graph.w2; i += 10 ) { graph.ctx.moveTo( i, j+0.5 ); graph.ctx.lineTo( i, j +5.5 ); } j = - 3; i = - graph.h2; for( i; i <= graph.h2; i += 10 ) { graph.ctx.moveTo( j+0.5, i ); graph.ctx.lineTo( j + 5.5, i ); } // alert('ticks') } if( orgin ){ graph.dot( 0, 0) // alert('orgin') } graph.ctx.stroke(); graph.ctx.beginPath(); return graph; } ; graph.dlog( 'axis drawing method initialized' ); graph.clrAll = function(){ graph.gs = []; graph.ctx.fillStyle="#eoffff" graph.ctx.fillRect( -graph.w2, -graph.h2, graph.w, graph.h ); graph.ctx.beginPath(); graph.dlog('graph cleared'); return graph; } graph.clrAll(); graph.dlog( 'axes drawn' ); graph.ec = function( /*y=*/equ ){ if( typeof equ !== "string" ) { alert( "Equation must be a string." ); return false; } equ = equ.replace( /\|([^\|]+)\|/g, "Math.abs($1)" ); equ = equ.replace( /([a-z0-9\.\-]+)\s*\^\s*([a-z0-9\.\-]+)/, "Math.pow($1,$2)" ); // eventually this will allow for normal human syntax equations and not only javascript syntax ones return equ; } ; graph.dlog( 'equation interpreter initialized' ); graph.graph = function( /*y=*/equ ){ equ = graph.ec( equ ); graph.ctx.strokeStyle='#800000'; if( equ === false ) { alert( 'Pass equation as a string without the "y=", "f(x)=", "g(x)=" or similar.' ); return graph; } var a=graph.lg; graph.gs[graph.gs.length] = equ; var i = 0; for( var x = 0 - graph.w2; x <= graph.w2; x ++ ) { try { var a=graph.lg; graph.lg[x] = eval(equ); } catch( e ) { alert(graph.dlog("Bad syntax!")); return graph } if( isNaN( graph.lg[x] ) || Math.abs( graph.lg[x] ) > graph.h2 ) { if(isNaN(graph.lg[x])){ i=0} } else{ if( i === 0 ){ graph.moveTo( x, graph.lg[x] ) i = 1; } else{ graph.lineTo( x, graph.lg[x]) graph.ctx.stroke(); } } } dlog('graphed '+equ); return graph; } ; graph.dlog( 'main graphing object initialized. \ngraph library finished. exiting grafit.js' ); return graph; } // --------------------------------------- ; it is used in this way Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=us-ascii" /> <link rel='stylesheet' href="jsgraphcalcstyle.css" type="text/css" /> <title>Javascript graphing calculator</title> <script type="text/javascript" src="untitled1.js"> </script> </head> <body> <script type="text/javascript" src='clik.js'> </script> <form id="form" action='javascript:graf()' onsubmit="graf()" name="form"> <h1>Javascript Graphing Calculator</h1> <div id="fakepad" class='back'> <div id='back'> <table summary="main structure"> <tr> <td colspan="4"><canvas id="screen" class='back' title='Graph' width="500" height="500"></canvas></td> </tr> <tr> <td colspan="2"> <span class="mem">f</span>(x) = <input type="text" class='back' id="equat" accesskey="f" /> </td> <td><button type="button" id="enter" value="Graph" onclick="graf()" accesskey="g"> <span class="mem">G</span>raph</button> </td> <td> <!-- <input type="button" id="clear" value="Clear" onclick="graph.clrAll();">--> <button type="button" id='clear' value='clear' onclick="clr();" accesskey="c"> <span class="mem">C</span>lear</button> </td> </tr> <tr> <td rowspan="2"> <input type="checkbox" id="showaxes" value="yes" checked='checked' onclick="clik()" accesskey="a" /> <label for="showaxes">Show <span class='mem'>a</span>xes</label> <!-- results in Show axes with the a underlined--> <br /> <input type='checkbox' id='showticks' value='yes' checked='checked' onclick='clik()' accesskey="t" /> <label for="showticks">Show <span class='mem'>t</span>ick marks</label> <!-- results in Show tick marks with the t underlined--> <br /> <input type="checkbox" id="showorgin" value="yes" disabled="disabled" onclick='da()' accesskey="o" /> <label for='showorgin' id='orginlab' class='dis'>Show <span class="mem">o</span>rgin</label> <!-- results in Show orgin with the o underlined--> <br /> </td> <td><!--spacer--></td><!--spacer--> <td><!--spacer--></td><!--spacer--> </tr> </table> </div> </div><!--inline div, requier <br>--> <br /> finish the function above and press Graph to graph it.<br /> Each tick mark on the graph is 10 units. <div id='debug' class="c2"> <textarea id='dlog' class="back" cols='70' rows="7" readonly="readonly"> </textarea><br /> <p class="c1">debugging log</p> </div><span><br /> <input type='button' id='dbut' onclick="dis()" value="Show debugging log" /></span> </form><script type="text/javascript" src='init.js'> </script> </body> </html> Hi, I managed to make a jquery drop down navigation system. I'm needing an opinion on the code as I suspect it could be alot cleaner and more efficient. A couple of niggling usability problems bug me - when a main link is in its active state and it is clicked on again it will slide up and then down again - I'd prefer it if it just stayed down and didn't move anywhere. The major thing that bugs me is if you think it breaks usability etiquette becuase the buttons move everywhere. If you think this is the case I will not use it. I understand there are forums for usability testing but if anyone has their opinions I'd be happy to hear them. You can view the navigation system he http://www.jrcreativedesign.co.uk/nav.html Thanks very much for your time and consideration. Hey guys, While I know you cannot use javascript for SEO, I need something similar. What I need is something like a search and replace program or something that does this: it takes aspects of the filename and incorparates it into the meta tags. For example, if a file was named "1x9.html" I would want it to edit the meta tag Season 1 Episode 9 I was just wondering if you guys know if such a thing exists. Like I would write a script or something in the program, saying for it to search and replace meta tags in file names, and it would 1. Analyze the filename (for this example it will be "1x9.html" 2. Input " Season 1 Episode 9 " into the meta tags (analyzing the first character in "1x9" as [Season] [First Character] , analyzing the "x" in 1x9 as [Episode] and analyzing the last character in "1x9" as [Last Character] I need to do this for like 80 thousand files, and I cannot do it 1 by 1. All of the elements that need to be in the meta tags already exist in the webpage contents or webpage filename. I was wondering if you guys know the best way for me to go about this? The following is inside a loop: Code: store1 = (Employees[i][3]==1)?'selected="true"':''; store2 = (Employees[i][3]==2)?'selected="true"':''; store3 = (Employees[i][3]==3)?'selected="true"':''; store4 = (Employees[i][3]==4)?'selected="true"':''; myTable+= '<td><select id="store' + i + '" onchange="" style="color:'+color1+' ; width:125px ; height:35px" >' +'<option ' + store1 + ' value="1">Pasadena</option>' +'<option ' + store2 + ' value="2">Alvin</option>' +'<option ' + store3 + ' value="3">Angleton</option>' +'<option ' + store4 + ' value="4">Bay City</option>' +'</select></td>' I originally came up with the idea in a similar part of the app that allowed choosing between employees and would ideally prefer something similar: Code: function BUILD_EMP_SELECTOR(){ empSelector = '<select id="empSelect" onchange="UPDATE_EMP();">'; for (i=1 ; i<AllEmployees.length ; i++){ Booleanselect = (i==me)?'selected="true"':''; empSelector += '<option ' + Booleanselect + ' value="' + i + '">' + AllEmployees[i] + '</option>'; } empSelector += '</select>'; ID('employee').innerHTML = empSelector; } The problem I'm having is that I would like to optimize the part of the first code that chooses which store a particular employee is at. I've also come up with this, but I'm not sure if its the best solution, or if it's even any better than my first: Code: store1=store2=store3=store4='';sel='selected="true"'; Employees[i][3]==1&&(store1=sel); Employees[i][3]==2&&(store2=sel); Employees[i][3]==3&&(store3=sel); Employees[i][3]==4&&(store4=sel); Also, while I would have to hard code additional stores +'<option ' + store5 + ' value="5">Elsewhere</option>' I would rather not have to add an additional "else if store5=" if possible. I know this is mostly code, and not much question, but what I'm looking for is mostly your opinions/recommendations... Ok, I have some extensive animation going on in this script. I have all the behavior I want out of this script. A 3D carousel interface, each window in the carousel is a separate UI window. It uses active scrolling for navs and content...like (iphone). The problem is that I have optimized to my best and still cant gain any performance out of IE. It runs pretty fast in FF, and in Safari. I have reversed loops, I have vared all my Math, I have stripped equations, could do more I guess, and I have made attempts at preventing even bubbling. I have minimized the use of <img> tags as well. I have even cached most methods and use a constructor method to create new HTML elements. At this point I am starting to feel like I am getting into techniques and areas of JS I just don't understand well. Here is example of a method I would like to optimize: Code: this.anim = function () { var s = Math.sin(s3D.A * .01); var c = Math.cos(s3D.A * .01); var xs = Math.round((s * this.x) + (c * this.z)); var zs = Math.round((s * this.z) - (c * this.x)); var ysSpeed = Math.round((s3D.Y - this.ys) / (s3D.speed * .1)); this.ys += ysSpeed; var D = nw / (nw + zs); var w = Math.round(D * (nw * s3D.zOOm)); var h = Math.round(w * s3D.HW); var Zac = Math.round(this.Z * nw * this.ac); var Zas = Math.round((this.Z * nw) * this.as); var calcOTop = px(Math.round(nh * .5 + this.ys * D - (h * .5))); var calcOtcTop = px(Math.round((h * .1 *D) - (w * .550))); var calcOleft = px(Math.round(nw * .5 + xs * D - (w * .5))); var calcOzindex = Math.round(D * 9); var pxW = px(w); var pxH = px(h); var barHeight = px(Math.round(h * .2)); var barFontSize = px(Math.round(.031 * w)); var otvHeight = px(Math.round(h * .091)); var oMenuHeight = "90%"; var calcOMenuLeft = px(Math.round(w * .1 *D -(w *.480))); var centerOtop = px(Math.round(nh * .4 + this.ys)); var centerOleft = "50%"; var floatLogotop = px(Math.round((nh * .68) + (this.ys + 20))); var floatLogoleft = "50%"; if(this.Z > .4 && this.dZ || this.pZ > 0){ var s3Dspeed = Math.round(s3D.A -= xs / 50); //s3Dspeed; } if(this.dZ){ this.Z *= 1.01; this.x = Zac; this.z = Zas; } if(this.Z > .8 && this.dZ){ this.dZ = false; this.pZ = s3D.temp; fadeOpacity("closeButton1"+newNID, 0, 100, 500); fadeOpacity("closeButton2"+newNID, 0, 100, 500); } if(this.dZ == false && this.Z > .4){ if(this.pZ > 0) { this.pZ--; } else { this.Z *= .995; this.x = Zac; this.z = Zas; } } Any Help? This is a fairly nasty piece of calculation. Any way to make this run faster? So, this code does what it's supposed to do (check an array for dis-allowed input and supply the appropriate keyboard for touchscreen users) but I was worried that maybe this wasn't the most succinct logic... Code: kb=2,kp=1; for(var i in Setup.DisAllowed){ if(Setup.DisAllowed[i]==0) kp=0; if(Setup.DisAllowed[i]==1||Setup.DisAllowed[i]==2) kb--; } if(kp)APP.Module('KeyPad'); if(kb)APP.Module('KeyBoard'); if(kp&&kb)APP.Module('AlphaNumeric'); Keeping in mind the Setup.DisAllowed array and APP.Module method are fixed in stone, would anyone recommend a better way to use the array to select the necessary keyboard? I'm trying to get a drop down box to change the image i've managed to get it working for one but can't seem to get it working when both scripts are on. any help would be much appreciated! http://humza-productions.co.uk/test/ this is the code i'm using, it's for the baseball jacket one but the one that's working live on the website is currently working for the hoodie Code: <script type="text/javascript"> window.onload=function() { bp='images/', //base url of your images imgnum=3, //Number of your images. This should match on your comboboxes options. thumb=document.getElementById('sho1'), //id of your image that will be changing combobox=document.getElementsByName('os1')[0]; // id of your combobox. combobox.onchange=function() { thumb.src=bp+'shop'+this.value+'.png'; } } </script> Hi all, Can some body help me i need a textbox and submit button.when i enter date in text box and click on submit button.Then my chart should display by passing my date(dynamic) through the code. how to design and code. Thanks.. Code: <script type="text/javascript"> var aURL = "http://xmegatop100.com/"; if (aURL == http://xmegatop100.com/) { document.write("<p style="text-align: right;"> <a href="{$list_url}/index.php">1-50</a> | <a href="{$list_url}/index.php?start=51">50-100</a> | <a href="{$list_url}/index.php?start=101">100-150</a> | <a href="{$list_url}/index.php?start=151">150-200</a></p> <br><br> "); } else { document.write("<p style="text-align: right;"> <a href="{$list_url}/index.php?cat={$category_url}&start=1">1-50</a> | <a href="{$list_url}/index.php?cat={$category_url}&start=51">50-100</a> | <a href="{$list_url}/index.php?cat={$category_url}&start=101">100-150</a> | <a href="{$list_url}/index.php?cat={$category_url}&start=151">150-200</a></p> <br><br> "); } </script> What im trying to do is if i have url as http://mysite.com then read1 code , if my site has http://mysite.com/index.php?cat=~~~~ Then reads the else part.. am i doing something wrong? this doesnt work.. Hello i have problem is i have penny auction script and i try to add auction and it show on indexpage assume 05-05-2011 but when the time hit 00.00 so date become to 6 and back to 5 in the morning maybe 12 hour and i try to change var.match round to var math.floor date become to 4 before midnight 2 minute and back to 5 when the time hit midnight again...so if this day is 5 and before midnight it will not become to 4 but when midnight come it will become to 6...so i dont know when item can end then this is code if someone can sort it out function calc_counter_from_time22(diff) { if (diff > 0) { hours=Math.floor(diff / 3600) minutes=Math.floor((diff / 3600 - hours) * 60) seconds=Math.round((((diff / 3600 - hours) * 60) - minutes) * 60) } else { hours = 0; minutes = 0; seconds = 0; } if(diff < 86400){ return twodigit(hours) + ":" + twodigit(minutes) + ":" + twodigit(seconds); } else{ var Tday = Math.floor(diff / (60 * 60 * 24)); var addDay = Tday; var d = new Date(); d.setDate(d.getDate()+addDay); mkMonth=d.getMonth()+1; mkMonth=new String(mkMonth); if(mkMonth.length==1){ mkMonth="0"+mkMonth; } mkDay=d.getDate(); mkDay=new String(mkDay); if(mkDay.length==1){ mkDay="0"+mkDay; } mkYear=d.getFullYear(); return mkDay+"-"+mkMonth+"-"+mkYear; } Hi everyone hope all well. I need your expertise. I have a problem with the email part of this javascript. Everything is working fine except for It will not validate when i add a period (.) before the @ sign. I am wanting to be able to put in an email like this abc.def@gmail.com or abc+def@gmail.com Here is the code for you to look at Code: <script type="text/javascript"> function validate_form() { if (!ValidatePhoneNumber(document.second.HomePhone.value)) { return false; } if(!ValidateZip(document.second.ZipCode.value)) { return false; } if ( document.second.degreeLevel.selectedIndex == 0 ) { alert ( "Please select degree level" ); return false; } if ( document.second.ProgramInterest.selectedIndex == 0 ) { alert ( "Please select area of study" ); return false; } if ( document.second.LevelofEducationCompleted.selectedIndex == 0 ) { alert ( "Please select level of education" ); return false; } if ( document.second.FirstName.value == '' ) { alert ( "Please Enter a First Name" ); return false; } if ( document.second.LastName.value == '' ) { alert ( "Please Enter a Last Name" ); return false; } if ( document.second.Address.value == '' ) { alert ( "Please Enter a Address" ); return false; } if ( document.second.City.value == '' ) { alert ( "Please Enter a City" ); return false; } if ( document.second.State.selectedIndex == 0 ) { alert ( "Please Select a State" ); return false; } if(!ValidateName(document.second.FirstName.value)) { return false; } if(!ValidateName(document.second.LastName.value)) { return false; } function ValidatePhoneNumber(field) { var valid = "0123456789"; var hyphencount = 0; if (field.length != 10) { alert("Please enter your 10 digits phone."); return false; } for (var i = 0; i < field.length; i++) { temp = "" + field.substring(i, i + 1); if (valid.indexOf(temp) == "-1") { alert("Invalid characters in your phone. Please try again."); return false; } } return true; } if(!EmailValid(document.second.Email.value)) { return false; } function ValidateZip(field) { var valid = "0123456789"; var hyphencount = 0; if (field.length!=5 ) { alert("Please enter your 5 digit zip code."); return false; } for (var i=0; i < field.length; i++) { temp = "" + field.substring(i, i+1); if (valid.indexOf(temp) == "-1") { alert("Invalid characters in your zip code. Please try again."); return false; } } return true; } function ValidateName(field) { var invalid="0123456789()-+=@#$%^&*!~`{}][|:;<>,?/"; for (var i=0; i < field.length; i++) { temp = "" + field.substring(i, i+1); if (invalid.indexOf(temp) != "-1") { alert("Invalid characters in your name field. Please try again."); return false; } } return true; } function EmailValid(email) { if(email=="") { alert("Email is required field!") return false } len = email.length if((email.charAt(1)=='.')||(email.charAt(1)=='@')||(email.charAt(1)=='.')) { alert("Invalid Email Please try again!") return false } if((email.charAt(len-2)=='@')||(email.charAt(len-2)=='.')) { alert("Invalid Email Please try again!") return false } count=0 dotcount=0 for (i=0; i< email.length; i++) { if(email.charAt(i)=='@') count++ if(email.charAt(i)=='.') dotcount++ } if((count !=1)||(dotcount !=1)) { alert("Invalid Email Please try again!") return false } return true } } </script> Im sure it is something small. i have tried changing things around but it will not work for me. Any help would be great. Thanks everyone Nim I am creating a web/shopping cart using Big Commerce. I am not a programer so I need help creating a code for the following: a.- PRICING DISOCOUNTS - The variations features allows for setting prices for diferent size, colors, etc. but will not allow for price discounts. Meaning if you buy 1 ea the price is $10.00 ea 2 $ 8.00 ea or 5 or more $ 7.00 ea. We sell health supplements so Price Discounts are important. Tech support said I needed a simple java cript code written. Need to give a set $$ discount or % discount to all products or individually as required. Can anyone help? I just started a small business but I am willing to pay some for quick delivery. Thank you very much. J.C. I have written the code below myself and im trying to figure out if this is the outcome in a web browser => 0 1 2 3 4 5 6 7 8 9 if not what would be the outcome? <script language=javascript type="text/javascript"> for (i=0 ;i<10 ;i++) { document.write(i) } </script> and how would you modify this code so it prints only even numbers and how would you modify it so that it sums all values of i and prints the final sum? Hi guys, as you can see i am newbie.. So ive been working with javascipt and html for about 2 days now. What im trying to do it make a really annoying website kind of like www.mudkipz.ws [go at your own risk], the site is a youtube video of mudkip pokemon that are really annoying they just say Mud-kip for about 9 minutes.. once you try to exit, messages pop up saying "Mud" And "Kip" After Clicking "ok" Its a Loop That goes on for ever! im trying to make something like this on dreamweaver but i have very little experience! Does anyone know how i could be able to make it so it can say [ "hahah i got you!" | |"Only way to exit is by going to this link" | | "Link" | |___________[ok]____________________ | Edit: I got the exit pop up message to work, now i just need the loop code! Any idea of how to put a link in the exit pop up message? Hello to all. I need someone to help me with making code for some page, because I don't know lot about coding. What I want is to this script work only when someone click on text like "Start script", not when someone open page where this script is. Can someone help me with that? Thanks a lot. Quote: <script type="text/javascript"> var win = window.open("http://www.mysite.com/", "mywindow"); var interval; function closePopup() { win.close(); clearInterval(interval); } interval=setInterval(closePopup,10000); </script> Hi guys my friend has created a game where there are four boxes each numbered from one to four. When you click on these boxes you either get a tick or a cross. In every turn 3 boxes will have ticks and one will have a cross and the aim is to get as many ticks as possible (each tick gets you a point and when you come across a cross your points are all deleted). Anyway i was wondering if theres a way to guess which box will have a cross beforehand. He claims its random but i wanted to make sure. heres the javascript: var spath; var failbox; var score; var pushnumber; var clickedEl; var clickedElT; var waitEvent = 1; function losegameget() { waitEvent = 1; $(".games3of4 > .box > div").each(function (boxli) { jQuery(this).removeClass("check"); jQuery(this).removeClass("check2"); jQuery(this).removeClass("heart"); jQuery(this).removeClass("heart2") }); jQuery(".savegame").css("visibility", "hidden"); $(".asama").find("span").html("0"); jQuery(clickedEl).removeClass("heart"); jQuery(clickedEl).removeClass("heart2"); $(".losebox").css("display", "block"); $(".box").css("display", "none"); jQuery.get("/game1of3"); jQuery.get("/game1of3?score=1", function (json) { var jsonall; eval("jsonall = " + json + ";"); jQuery("#scoreliste").html(""); for (var i = 0; i < jsonall.length; i++) { jQuery("#scoreliste").append(jQuery('<li><div class="order">' + (i + 1) + "</div> " + jsonall[i]["username"] + " <span>(" + jsonall[i]["score"] + ")</span></li>")) } }); } function gameget() { var dd = $(".asama").find("span").text(); if (dd == "0") { $(".asama").find("span").text(0); } score = eval($(".asama").find("span").text()); $(".asama").find("span").empty().html(score + 1); $(".games3of4 > .box > div").each(function (boxli) { jQuery(this).removeClass("check"); jQuery(this).removeClass("check2"); }); waitEvent = 1; } function wgame() { waitEvent = 0; $(".games3of4 > .box > div").each(function (a) { jQuery(this).removeClass("check"); jQuery(this).removeClass("check2"); }); if (parseInt(jQuery(clickedEl).attr("rel")) == 1 || parseInt(jQuery(clickedEl).attr("rel")) == 2) { jQuery(clickedEl).addClass("check") } if (parseInt(jQuery(clickedEl).attr("rel")) == 3 || parseInt(jQuery(clickedEl).attr("rel")) == 4) { jQuery(clickedEl).addClass("check2") } setTimeout("gameget();", 200); } function losegame() { waitEvent = 0; $(".games3of4 > .box > div").each(function (a) { jQuery(this).removeClass("check"); jQuery(this).removeClass("check2"); jQuery(this).removeClass("heart"); jQuery(this).removeClass("heart2"); }); if (parseInt(jQuery(clickedEl).attr("rel")) == 1 || parseInt(jQuery(clickedEl).attr("rel")) == 2) { jQuery(clickedEl).addClass("heart"); } if (parseInt(jQuery(clickedEl).attr("rel")) == 3 || parseInt(jQuery(clickedEl).attr("rel")) == 4) { jQuery(clickedEl).addClass("heart2"); } setTimeout("losegameget();", 400); } function ifagain() { jQuery(".box").hide(); jQuery(".savegame").hide(); jQuery(".asama").hide(); jQuery("#againcall").show(); jQuery(".yes").click(function () { jQuery.get("/game1of3?start=1", function () { jQuery(".box").show(); jQuery("#againcall").hide(); jQuery(".savegame").css("visibility", "visible"); jQuery(".asama").show(); }) }) } function playSound(a) {} jQuery.jQueryRandom = 0; jQuery.extend(jQuery.expr[":"], { random: function (c, d, b, e) { if (d == 0) { jQuery.jQueryRandom = Math.floor(Math.random() * e.length) } return d == jQuery.jQueryRandom; } }); function countGet() { jQuery.get("/game1of3?count=1", function (a) { jQuery("#defa").html(a + " Defa Oynandı<br />"); }) } $(document).ready(function () { setInterval("countGet();", 20000); jQuery(".savegame").click(function () { if (confirm("Puanınızı kaydetmek istediğinizden emin misiniz ?")) { jQuery.get("/game1of3?save=1", function () { jQuery(".box").hide(); jQuery("#saved").show(); jQuery(".boxaga").show(); jQuery(".savegame").css("visibility", "hidden"); $(".highpoint").find("b").html($(".asama").find("span").text()); $(".asama").find("span").html("0"); }) } }); z = 0; $(".games3of4 > .box > div").each(function (boxli) { $(this).click(function () { if (waitEvent) { clickedEl = this; clickedElT = jQuery(this).attr("rel"); jQuery.get("/game1of3?res=" + jQuery(this).attr("rel"), function (data) { if (data == 'umustbelogin') { window.location.href = '/uye/giris?&redirect_to=/oyun'; } else { var r; r = (data.indexOf("true") != -1); } if (r) { wgame(); } else { losegame(); } }) } }); }); $(".try").click(function () { $(".losebox").css("display", "none"); $(".box").css("display", "block"); jQuery(".savegame").css("visibility", "visible"); }); $(".try2").click(function () { $(".boxaga").css("display", "none"); $(".box").css("display", "block"); jQuery("#saved").hide(); jQuery(".savegame").css("visibility", "visible"); }); $.playgame = function (kcode) { score = eval($(".score").find("span").text()); if (kcode == 49) { pushnumber = 1 } if (kcode == 50) { pushnumber = 2 } if (kcode == 51) { pushnumber = 3 } if (kcode == 52) { pushnumber = 4 } clickedEl = $(".gamecontent li")[pushnumber - 1]; clickedElT = pushnumber; jQuery.get("/game1of3?res=" + pushnumber, function (data) { score = eval($(".score").find("span").text()); var r = eval(data); if (r) { wgame(); } else { losegame(); } }) }; jQuery.get("/game1of3"); }); cheers! Ok this is supposed to be a slot machine that works when I click the "Slot" button. If all the images match, then it is supposed to say "Congratulations...". If all the images do not match, then it is supposed to say "Sorry, you lose....". For one thing, I want the images to load after I hit the slot button and not when I refresh the page. Also, I've screwed up somewhere and I think I need another function option but I don't know where to put it or what to do. And last, my if, else statement isn't working. I'm pretty much new to Javascript and I don't know if the way I assigned the images to variables is even correct. Someone please help me. It would greatly appreciated. PHP Code: <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Slot Machine</title> <style type = "text/css"> table { width: 45em } th { text-align: left } th { text-align: center } th { text-align: right } div.red { color: red } </style> <script type = "text/javascript"> <!-- var pictures = [ "star", "blueSeven", "berry" ]; var pic1; var pic2; var pic3; pic1 = document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 3 ) ] + ".gif\" />" ); pic2 = document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 3 ) ] + ".gif\" />" ); pic3 = document.write ( "<img src = \"" + pictures[ Math.floor( Math.random() * 3 ) ] + ".gif\" />" ); function play() { var statusDiv = document.getElementById( "status" ); if ( pic1 = pic2 ) { if ( pic2 = pic3 ) statusDiv.innerHTML = "Congratulations, you win!"; } else statusDiv.innerHTML = "Sorry, you lose. " + "Please try again."; } </script> </head> <body> <form action = ""> <table> <tr><td /><td><input type = "button" value = "Slot" onclick = "play()" /></td></tr> </table> <div id = "status" class = "red"> Click the Slot button to play</div> </form> </body> </html> Hi there, I'm sure someone can help me with this simple fix. I am putting a site together for a friend and I found a Javascript code that I'm using which basically causes an image to enlarge on mouse rollover. The website, which I just started, is: Home 2 What I'm trying to do is get the larger image to appear a little more to the right than it currently does, so it is not right on top of the thumbnails. I hope someone can tell me what code (and where) I need to add to accomplish this. I'm quite new at this so I really need specific instruction. Thanks in advance for your help! Here is the code for the onmouseover routine: Code: <head> <script language="JavaScript"> function showlargeimage(imgshow) {document.getElementById('image').src=imgshow;} function showlargeimage(imgshow) {document.getElementById('image').src=imgshow; document.getElementById('image').style.display='block'; } </script> </head> <body> <TABLE> <TR> <TD> <!--THUMBNAILS--> <img src="thumbnail1.jpg" onmouseover=showlargeimage('image1.jpg')><br> <br> <img src="thumbnail2.jpg" onmouseover=showlargeimage('image2.jpg')><br> <br> <img src="thumbnail3.jpg" onmouseover=showlargeimage('image3.jpg')><br> <br> <img src="thumbnail4.jpg" onmouseover=showlargeimage('image4.jpg')><br> <br> <img src="thumbnail5.jpg" onmouseover=showlargeimage('image5.jpg')><br> <br> </TD> <TD> <!--image SCREEN--> <img src='#' id='image'> <img src='#' id='image' style='display:none'> </TD> </TR> </TABLE> </body> Hi, Which is the difference between to use "<!-- //-->" inside the script or not? Quote: <script language=JavaScript> <!-- function stopError() { return true; } window.onerror = stopError; // --> </script> Quote: <script language=JavaScript> function stopError() { return true; } window.onerror = stopError; </script> Any advice is welcome!! stickers Code below is not working...nothing happens on clicking submit...javascript is enabled in browser..help please. Code: <html> <head> <script type="text/javascript"> function match() { var aa=document.getElementById("username").Value; var bb=document.getElementById("password").Value; if(aa==null || bb==null) { alert("Enter Again"); } else if((aa=="admin") && (bb=="12345")) { Alert("Hello Sir"); } else if((aa=="guest") && (bb=="67890")) { Alert("Hello Guest"); } else { Alert("Enter Valid Info"); } } </script> </head> <body> Username:<input type="text" id="username"/><br/> Password:<input type="text" id="password"/><br/> <input type="submit" onClick="match()"/> </body> </html> |