JavaScript - I Need Major Code Optimization.
i 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> Similar TutorialsHey 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. 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. I have a function which allows the number of buttons selected depending on the number selected from the drop down menu. Problem is that this code works in all of the major browsers except for Internet Explorer (No Suprise). For example if user chose the number 3 from the dropdown menu, then user can only select 3 buttons. Why is it not working in Internet explorer and what can be used to make it work in Internet Explorer? Below is javascript functions: Code: function getButtons() { document.getElementById("answerA").class="answerBtnsOff"; document.getElementById("answerA").setAttribute("class","answerBtnsOff"); document.getElementById("answerA").setAttribute("className","answerBtnsOff"); document.getElementById("answerB").class="answerBtnsOff"; document.getElementById("answerB").setAttribute("class","answerBtnsOff"); document.getElementById("answerB").setAttribute("className","answerBtnsOff"); document.getElementById("answerC").class="answerBtnsOff"; document.getElementById("answerC").setAttribute("class","answerBtnsOff"); document.getElementById("answerC").setAttribute("className","answerBtnsOff"); document.getElementById("answerD").class="answerBtnsOff"; document.getElementById("answerD").setAttribute("class","answerBtnsOff"); document.getElementById("answerD").setAttribute("className","answerBtnsOff"); document.getElementById("answerE").class="answerBtnsOff"; document.getElementById("answerE").setAttribute("class","answerBtnsOff"); document.getElementById("answerE").setAttribute("className","answerBtnsOff"); currenttotal=0; } function btnclick(btn) { if(document.getElementById("numberDropId").value=="") { alert('You must first select the number of answers you require from the drop down menu'); return false; } if (btn.class=="answerBtnsOn") { btn.class="answerBtnsOff"; btn.setAttribute("class","answerBtnsOff"); btn.setAttribute("className","answerBtnsOff"); currenttotal--; return false; } if(document.getElementById("numberDropId").value==currenttotal) { alert('You are not allowed beyond the limit of the number of answers you require, deselect other button'); return false; } if (btn.class=="answerBtnsOff") { btn.class="answerBtnsOn"; btn.setAttribute("class","answerBtnsOn"); btn.setAttribute("className","answerBtnsOn"); currenttotal++; return false; } } If you html code then this is below: Code: <form id="enter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validateForm(this);" > <table id="middleDetails" border="1"> <tr> <td>Question:</td> <td rowspan="3"> <textarea rows="5" cols="40" name="questionText"></textarea> </td> <td>Option Type:</td> <td> <select name="optionDrop" onClick="getDropDown()"> <option value="">Please Select</option> <option value="abc">ABC</option> <option value="abcd">ABCD</option> <option value="abcde">ABCDE</option> <option value="trueorfalse">True or False</option> <option value="yesorno">Yes or No</option> </select> </td> <tr> <td colspan="2"></td> <td>Number of Answers:</td> <td> <span id="na">N/A</span> <select name="numberDrop" id="numberDropId" onChange="getButtons()"> <option value=""></option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select> </td> </tr> </table> </form> 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... 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? 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? 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? Hi there i would be most most grateful if someone could edit this code so that it accepts the inputs from the marks fields to calculate the mean and standard deviation. thanks in advance, chris ********************************************************* <html> <head> <title>Student Result Processor</title> <style type="text/css"> body { background-image:url('Background.jpg') } .container { text-align:center; margin: 10px auto; } .content { width: 400px; } </style> <script language="javascript"> function addRow() { var newRow = document.all("tblGrid").insertRow(); var oCell = newRow.insertCell(); oCell.innerHTML = "<input type='text' name='t1' size='10'>"; oCell = newRow.insertCell(); oCell.innerHTML = "<input type='text' name='t2' size='20'>"; oCell = newRow.insertCell(); oCell.innerHTML = "<input type='text' name='t3' size='5'>"; oCell = newRow.insertCell(); oCell.innerHTML = "<input type='button' value='Delete' onclick='removeRow(this);'/>"; } function removeRow(src) { var oRow = src.parentElement.parentElement; document.all("tblGrid").deleteRow(oRow.rowIndex); } </script> </head> <body> <div class="container"> <div class="content"> <hr> <table id="tblGrid"> <tr> <td class="container">SID</td> <td class="container">NAME</td> <td class="container">MARK</td> <td></td> </tr> </table> <hr> <input type="button" value="Add Row" onClick="addRow();" /><br /> <input type="button" Value="Calculate" onClick="calc();" /> <hr> </div> </div> </body> <script type = "text/javascript"> function calc() { var data = [2,3,4,6,7]; var deviation = []; var sum = 0; var devnsum = 0; var stddevn = 0; var len = data.length; for (var i=0; i<len; i++) { sum = sum + (data[i] * 1) // ensure number } var mean = (sum/len).toFixed(6); // 6 decimal places for (i=0; i<len; i++) { deviation[i] = data[i] - mean; deviation[i] = deviation[i] * deviation[i]; devnsum = devnsum + deviation[i]; } stddevn = Math.sqrt(devnsum/(len-1)).toFixed(6); // 6 decimal places alert ("The mean is: " + mean + " The standard deviation is: " + stddevn); } </script> </html> ********************************************************* My professor asked us to make a webpage that has a user register and login in via a xml document. We can omly use html, javascrip and css. I made a function that loads users from an xml file and authenticates them. It works only on firefox and not IE. This is a problem because i am using ActiveXobject to write to the file. Any help will greatly be appreciated. Here is my function that loads xml: Code: function ReadXML() { try { xmlDoc = loadMyXML("xmlStudent.xml"); } catch (objerr) { alert(objerr.description); } xmlfile = xmlDoc.getElementsByTagName('student'); fname= xmlDoc.getElementsByTagName("firstname"); lname= xmlDoc.getElementsByTagName("lastname"); usernames = xmlDoc.getElementsByTagName("username"); passwords = xmlDoc.getElementsByTagName("password"); } Here is the xmlfile Code: <?xml version="1.0" encoding="utf-8"?> <!--My first xml file (^-^) --> <CST2309> <student> <firstname>bob</firstname> <lastname>harris</lastname> <username>admin111</username> <password>11111111</password> </student> <student> <firstname>joe</firstname> <lastname>smith</lastname> <username>joe222</username> <password>22222222</password> </student> <student> <firstname>sarah</firstname> <lastname>diaz</lastname> <username>sarah333</username> <password>33333333</password> </student> <student> <firstname>katie</firstname> <lastname>adams</lastname> <username>katie444</username> <password>44444444</password> </student> </CST2309> Our site has quite a few 'features' to it. One is a drop down menu at the top of the site, another is an AJAX add to cart thing that loads the product to the cart without refreshing the page. Here's the problem. If someone adds a product to the cart and goes to view the cart, the space where the cart information usually is will be empty. The sidebar, top navigation, footer, all that, is still there. The cart info itself is gone. What we have noticed is if you add say 2 different products to the cart, view the cart (empty page at this point), and then use the drop down cart summary in the header to remove a product from the cart summary, the cart info will all of a sudden appear as it should. Refresh the page and it goes away again. It seems like removing the product from the cart summary in the header forces the AJAX add to cart feature to re-load the cart bringing it back. It just isn't loading initially. We have no idea why it quit working. It has been working for nearly two months with no problem. Here is a link to the site, you can test it yourself. soundisolationstore dot com The checkout works fine, just not the cart page. Please help if you can! This post will contain a few guidelines for what you can do to get better help from us. Let's start with the obvious ones: - Use regular language. A spelling mistake or two isn't anything I'd complain about, but 1337-speak, all-lower-case-with-no-punctuation or huge amounts of run-in text in a single paragraph doesn't make it easier for us to help you. - Be verbose. We can't look in our crystal bowl and see the problem you have, so describe it in as much detail as possible. - Cut-and-paste the problem code. Don't retype it into the post, do a cut-and-paste of the actual production code. It's hard to debug code if we can't see it, and this way you make sure any spelling errors or such are caught and no new ones are introduced. - Post code within code tags, like this [code]your code here[/code]. This will display like so: Code: alert("This is some JavaScript code!") - Please, post the relevant code. If the code is large and complex, give us a link so we can see it in action, and just post snippets of it on the boards. - If the code is on an intranet or otherwise is not openly accessible, put it somewhere where we can access it. - Tell us any error messages from the JavaScript console in Firefox or Opera. (If you haven't tested it in those browsers, please do!) - If the code has both HTML/XML and JavaScript components, please show us both and not just part of it. - If the code has frames, iframes, objects, embeds, popups, XMLHttpRequest or similar components, tell us if you are trying it locally or from a server, and if the code is on the same or different servers. - We don't want to see the server side code in the form of PHP, PERL, ASP, JSP, ColdFusion or any other server side format. Show us the same code you send the browser. That is, show us the generated code, after the server has done it's thing. Generally, this is the code you see on a view-source in the browser, and specifically NOT the .php or .asp (or whatever) source code. I'm trying to get my Client Side Firefox DHTML app to display a list of eBooks. For this, i have the following files F:\Textbooks.html F:\eBooks.txt F:\FirstBook.txt F:\SecondBook.txt F:\ThirdBook.txt textbooks.html is my DHTML app eBooks.txt is the Library file with a listing of all of my eBooks. Inside of eBooks.txt is the following data: ----------------- FirstBook.txt, SecondBook.txt, ThirdBook.txt, ----------------- FirstBook.txt to ThirdBook.txt are my actual ebooks. The problem that i'm having is that When i try to click on any buttons other than the FirstBook button, i get the following error: ---------------------------------- Error: unterminated string literal Source File: file:///F:/Textbooks.html Line: 1, Column: 10 Source Code: LoadEbook(' ---------------------------------- So, unlike clicking on the FirstBook button, these other buttons do not load the eBook data into the DIV for displaying the eBook data. I use the DOM insepector to checkout the DOM of the button code, and it seems like whitespace maybe is the problem. However, i have removed whitespace from the HTMLdata string, and that's not fixing the problem. did i forget something silly? LOL i'm using FireFox 3.5 to develop this App. So obviously this will not work with anything other than Gecko Based browsers. here is my HTML code: <html> <head> <script language="JavaScript"> var eBookLibrary = "eBooks.txt"; var SystemPath = "f:" + String.fromCharCode(92) function Init() { // Initialize the eBook reader document.getElementById("EbookCanvas").style.visibility = "hidden"; document.getElementById("EbookToolbar").style.visibility = "visible"; document.getElementById("FileManager").style.visibility = "visible"; // Load the List of eBooks in the Library LoadBookList(); } function UpdateEbookList() { // Update the Library of Ebooks alert("Updating eBook Library"); // Go back to the File Manager, and Reload the List of Ebooks LoadBookList(); } function LoadBookList() { // This will load the list of books that are available var EbookList = LoadFromDisk(SystemPath + eBookLibrary); var EbookListArray = EbookList.split(","); for(var x = 0; x < EbookListArray.length -1; x++) { // Strip the Filename Extension off of the eBook File Name // The Name of the Book is always the first Index in the Array var BookName = EbookListArray[x].split("."); // Remove the weird whitespace - it screws things up...i think... BookName[0] = BookName[0].replace(/(^\s*|\s*$)/g, ""); var HTMLdata = HTMLdata + "<input type='button' value='" + "FirstBook" + "'" + " onClick=LoadEbook('" + EbookListArray[x] + "');><br>"; } // For some ****ed up reason the first string always generates an 'undefined' even though it's nonsense // So just delete that from the HTMLdata string, because it's just ugly - LOL HTMLdata = HTMLdata.replace("undefined", ""); HTMLdata = HTMLdata.replace("", " "); // Write the HTML data to the DIV document.getElementById("FileManager").innerHTML = HTMLdata; } function LoadEbook(EbookName) { // Hide the File Manager and Show the Ebook Canvas document.getElementById("FileManager").style.visibility = "hidden"; document.getElementById("EbookCanvas").style.visibility = "visible"; document.getElementById("EbookToolbar").style.visibility = "visible"; // Load the Ebook content into the Ebook Reader Pannel var EbookContent = LoadFromDisk(SystemPath + EbookName); document.getElementById("EbookCanvas").innerHTML = EbookContent; } function LoadFromDisk(filePath) { if(window.Components) try { netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); file.initWithPath(filePath); if (!file.exists()) return(null); var inputStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); inputStream.init(file, 0x01, 00004, null); var sInputStream = Components.classes["@mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream); sInputStream.init(inputStream); return(sInputStream.read(sInputStream.available())); } catch(e) { //alert("Exception while attempting to load\n\n" + e); return(false); } return(null); } </script> </head> <body onLoad="Init();"> <div id="FileManager" style="position: absolute; top: 0px; left: 0px; visibility: visible;"> The eBook Library's List of Books will be listed here. Click on one to open it in the eBook Reader </div> <br> <div id="EbookCanvas" style="position: absolute; top: 0px; left: 0px; visibility: hidden;"> </div> <br> <div id="EbookToolbar" style="position: absolute; top: 100px; left: 0px;"> <input type="button" value="Open" OnClick="Init();"> <input type="button" value="Update" OnClick="UpdateEbookList();"> <input type="button" value="Exit" OnClick="MainMenu();"> </div> </body> </html> Hi all, I hope someone can advise whether such a script exists for what am wanting to do. From time to time, I need to send password information or login details and password information to some users. At the moment, am doing it via email with a subject named FYI and the body of the email basically just contain the login and the password or in some case, just the password. What am wanting to know is whether I can put these information into a HTML file which contains an obfuscated Javascript with a button that a user will click that will prompt for his login information and then will display the password. In its simplest form, I guess I am looking for a Javascript that will obfuscate a HTML file that contains the password. Anyway, hopefully someone understand what am looking for. I found some website that offers such service as obfuscating a HTML file but am hoping it can be done via a Javascript so it is at least "portable" and I do not have to be online. Any advice will be much appreciated. Thanks in advance. Hi guys.. I really need a bit of help.. is anyone looking at this good with JS? I have a php form validation script but i think its a bit slow and would rather a JS script instead... here is what i have in php.. PHP Code: <?php if(isset($_POST['submit'])) { $firstName = $_POST['firstName']; $lastName = $_POST['lastName']; $email = $_POST['email']; $mobile = $_POST['mobile']; $comments = $_POST['comments']; $errors = array(); function display_errors($error) { echo "<p class=\"formMessage\">"; echo $error[0]; echo "</p>"; } function validateNames($names) { return(strlen($names) < 3); } function validateEmail($strValue) { $strPattern = '/([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4})/sim'; return(preg_match($strPattern,$strValue)); } function validateMobile($strValue) { $strPattern = '/^\d{10}$/'; return(preg_match($strPattern,$strValue)); } function validateComments($comments) { return(strlen($comments) < 10); } if(validateNames($firstName)) { $errors[] = 'Please Enter Your First Name'; } if(validateNames($lastName)) { $errors[] = 'Please Enter Your Second Name'; } if(!validateEmail($email)) { $errors[] = 'Please Enter Your Correct Email'; } if(!validateMobile($mobile)) { $errors[] = 'Please Enter Your Correct Mobile Number'; } if(validateComments($comments)) { $errors[] = 'Please Enter A Comment More Than 10 Characters'; } if(empty($errors)) { $to = "info@eventpromotion.ie"; $subject = "Event Promotion Enquiry!"; $body = "First Name: " . $_POST['firstName'] . "\nLast Name: " . $_POST['lastName'] . "\nEmail: " . $_POST['email'] . "\nMobile: " . $_POST['mobile'] . "\nMessage: " . $_POST['comments']; $headers = "From: ". $firstName ." ". $lastName . " <" . $email . ">\r\n"; if (mail($to, $subject, $body, $headers)) { echo("<p class=\"formMessage\">Thanks for submitting your enquiry.</p>"); } else { echo("<p class=\"formMessage\">Message delivery failed.</p>"); } } else { //echo "error"; display_errors($errors); } } ?> <form id="form" method="post" action="index.php#quickContact"> <p> <label>First Name</label><br /> <input type="text" name="firstName" value="<?php if(isset($firstName)){echo $firstName;} ?>" /> </p> <p> <label>Last Name</label><br /> <input type="text" name="lastName" value="<?php if(isset($lastName)){echo $lastName;} ?>" /> </p> <p> <label>Email:</label><br /> <input type="text" name="email" value="<?php if(isset($email)){echo $email;} ?>" /> </p> <p> <label>Mobile:</label><br /> <input type="text" name="mobile" value="<?php if(isset($mobile)){echo $mobile;} ?>" /> </p> <p> <label>Comments:</label> <br /> <textarea name="comments" cols="30" rows="3" ><?php if(isset($comments)){echo $comments;} ?></textarea> </p> <p> <input class="send" type="image" src="images/submit2.gif" name="submit" value="Submit" /></p> </form> does anyone know how to transfer this to JS so that it will be easy to understand.. Im not good with JS at all I am trying to set up a looping structure that tests to see if the user enters a value. If the textbox is null then a global variable is false otherwise a checkbox is checked and the global variable is true. below is what i have done so far, please assist me. var isValid = false; window.onload = startForm; function startForm() { document.forms[0].firstName.focus(); document.forms[0].onsubmit = checkEntries; alert("You have been added to the list") } function checkEntries() { var menus = new Array(); var formObject = document.getElementsByTagName('*'); for (var i=0; i < formObject.length; i++){ if (formObject[i] == "myform") menus.push(formObject[i]); if (document.forms[0].firstName.value.length==0 || document.forms[0].firstName.value.length == null){ isValid= false; alert("Please enter a first name"); } else (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].lastName=="" || document.forms[0].lastName== null){ alert("Please enter a last name"); isValid = false; } else (document.forms[0].check1.checked=true); isValid=true; if (document.forms[0].email=="" || document.forms[0].email== null) { alert("Please enter a valid email"); } else return (document.forms[0].check0.checked=true); isValid=true; if (document.forms[0].bDate=="" || document.forms[0].bDate== null) { isValid=false; alert("please make sure you enter a valid birth date."); } else (document.forms[0].check0.checked=true); isValid=true; } } here is the form html... <form name="myform" > <input type="checkbox" name="check0" class="check0" id="check0" > First: <input type="text" name="firstName" id="firstName"> <BR> <input type="checkbox" name="check1" class="check1" id="check1" > Last: <input type="text" name="lastName" id="lastName" ><BR> <input type="checkbox" name="check2" class="check2" id="check2" > E-Mail: <input type="text" name="email" id="email"> <BR> <input type="checkbox" name="check3" class="check3" id="check3" > Birthday (mm/dd/yyyy): <input type="text" name="bDate" id="bDate"> <BR> <input type="submit" value="Join our mailing List" /> </form> Hey everyone here is my code for looking up a city, and state by zip code. I am getting no errors and i believe it should work, but the code does not seem to want to function. Any ideas? Here is my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>City and State Lookup</title> <style type="text/css"> h1 { font-family:Arial; color:navy; } p, td { font-family:arial; font-size:11px; } </style> <script type="text/javascript"> /* <![CDATA[ */ var httpRequest = false; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); } catch (requestError) { try { httpRequest = new ActiveXObject ("Msxm12.XMLHTTP"); } catch (requestError) { try { httpRequest = new ActiveXObject ("Microsoft.XMLHTTP"); } catch (requestError) { window.alert("Your browser does not support AJAX!"); return false; } } } return httpRequest; } function updateCityState() { if (!httpRequest) httpRequest = getRequestObject(); httpRequest.abort(); httpRequest.open("get","zip.xml"); httpRequest.send(null); httpRequest.onreadystatechange=getZipInfo; } function getZipInfo() { if (httpRequest.readyState==4 && httpRequest.status == 200) { var zips = httpRequest.responseXML; var locations = zips.getElementsByTagName("Row"); var notFound = true; for (var i=0; i<locations.length; ++i) { if (document.forms[0].zip.value == zips.getElementsByTagName( "ZIP_Code")[i].childNodes[o].nodeValue) { document.forms[0].city.value = zips.getElementsByTagname( "City") [i].childNodes[0].nodeValue; document.forms[0].state.value = zips.getElementByTagName( "State_Abbreviation")[i].childNodes[0].nodeValue; notFound = flase; break; } } if (notFound) { window.alert("Invalid ZIP code!"); document.forms[0].city.value = ""; document.forms[0].state.value = ""; } } } /* ]]> */ </script> </head> <body> <h1>City and State Lookup </h1> <form action=""> <p>Zip code <input type="text" size="5" name="zip" id="zip" onblur="updateCityState()" /></p> <p>City <input type="text" name="city" /> State <input type="text" size="2" name="state" /></p> </form> </body> </html> Ok guys if you look at this page www.runningprofiles.com/members/shout/view.php my code works great.... But when i add it to the rest of the script the code wont work shows he http://www.runningprofiles.com/membe...ll_Script.php# Below is view.php (the one that works) and the one added to the code scirpt is the one the does not. PHP Code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript"> $(function() { $(".view_comments").click(function() { var ID = $(this).attr("id"); $.ajax({ type: "POST", url: "viewajax.php", data: "msg_id="+ ID, cache: false, success: function(html){ $("#view_comments"+ID).prepend(html); $("#view"+ID).remove(); $("#two_comments"+ID).remove(); } }); return false; }); }); </script> <ol> <?php //Here $id is main message msg_id value. $csql=mysql_query("select * from comments where msg_id_fk='130' order by com_id "); $comment_count=mysql_num_rows($csql); if($comment_count>2) { $second_count=$comment_count-2; ?> <div class="comment_ui" id="view130"> <a href="#" class="view_comments" id="130">View all <?php echo $comment_count; ?> comments</a> </div> <?php } else { $second_count=0; } ?> <div id="view_comments130"></div> <div id="two_comments130"> <table width="30%"> <?php $small=mysql_query("select * from comments where msg_id_fk='130' order by com_id limit $second_count,2 "); while($rowsmall=mysql_fetch_array($small)) { $c_id=$rowsmall['com_id']; $comment=$rowsmall['comment']; ?> <div class="comment_actual_text"> <tr> <td style="BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; BORDER-LEFT: black 1px solid; BORDER-BOTTOM: black 1px solid" valign="top"> <table style="WIDTH: 100%; BORDER-COLLAPSE: collapse" align="left"> <tr> <td width="5%" style="VERTICAL-ALIGN: middle; TEXT-ALIGN: center"><img style="WIDTH: 30px; HEIGHT: 30px" alt="srinivas" src="http://www.gravatar.com/avatar.php?gravatar_id=7a9e87053519e0e7a21bb69d1deb6dfe" border="1" /></td> <td style="VERTICAL-ALIGN: top; TEXT-ALIGN: left"> <strong>Jarratt</strong> <?php echo $comment; ?> <br /><span style="COLOR: #a9a9a9">10 min ago - ID = <?php echo $c_id;?> </span></td> </tr> </table><br /> </td> </tr> </div> <?php } ?> </table> </div> </ol> Facebook_Wall_Script.php PHP 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=iso-8859-1" /> <title>9lessons Applicatio Demo</title> <link href="frame.css" rel="stylesheet" type="text/css"> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script> <script type="text/javascript" src="jquery.oembed.js"></script> <script type="text/javascript"> <script type="text/javascript"> $(function() { $(".view_comments").click(function() { var ID = $(this).attr("id"); $.ajax({ type: "POST", url: "../viewajax.php", data: "msg_id="+ ID, cache: false, success: function(html){ $("#view_comments"+ID).prepend(html); $("#view"+ID).remove(); $("#two_comments"+ID).remove(); } }); return false; }); }); $(function() { $(".comment_button").click(function() { var element = $(this); var boxval = $("#content").val(); var dataString = 'content='+ boxval; if(boxval=='') { alert("Please Enter Some Text"); } else { $("#flash").show(); $("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>'); $.ajax({ type: "POST", url: "update_ajax.php", data: dataString, cache: false, success: function(html){ $("ol#update").prepend(html); $("ol#update li:first").slideDown("slow"); document.getElementById('content').value=''; $('#content').value=''; $('#content').focus(); $("#flash").hide(); $("#expand_url").oembed(boxval); } }); } return false; }); / Delete Wall Update $('.delete_update').live("click",function() { var ID = $(this).attr("id"); var dataString = 'msg_id='+ ID; var parent=$("#bar"+ID); jConfirm('Are you sure you want to delete this message?', 'Confirmation Dialog', function(r) { if(r==true) { $.ajax({ type: "POST", url: "delete_update.php", data: dataString, cache: false, success: function(html){ parent.slideUp(300,function() { parent.remove(); }); } }); } }); return false; });//comment slide $('.comment').live("click",function() { var ID = $(this).attr("id"); $(".fullbox"+ID).show(); $("#c"+ID).slideToggle(300); return false; }); //commment Submint $('.comment_submit').live("click",function() { var ID = $(this).attr("id"); var comment_content = $("#textarea"+ID).val(); var dataString = 'comment_content='+ comment_content + '&msg_id=' + ID; if(comment_content=='') { alert("Please Enter Comment Text"); } else { $.ajax({ type: "POST", url: "comment_ajax.php", data: dataString, cache: false, success: function(html){ $("#commentload"+ID).append(html); document.getElementById("textarea"+ID).value=''; $("#textarea"+ID).focus(); } }); } return false; }); // Delete Wall Update $('.delete_update').live("click",function() { var ID = $(this).attr("id"); var dataString = 'msg_id='+ ID; var parent=$("#bar"+ID); jConfirm('Are you sure you want to delete this message?', 'Confirmation Dialog', function(r) { if(r==true) { $.ajax({ type: "POST", url: "delete_comment.php", data: dataString, cache: false, success: function(html){ $("#comment"+ID).slideUp(); } }); } return false; }); return false; }); </script> <style type="text/css"> body { font-family:Arial, Helvetica, sans-serif; font-size:12px; } .update_box { background-color:#D3E7F5; border-bottom:#ffffff solid 1px; padding-top:3px } a { text-decoration:none; color:#d02b55; } a:hover { text-decoration:underline; color:#d02b55; } *{margin:0;padding:0;} ol.timeline {list-style:none;font-size:1.2em;}ol.timeline li{ display:none;position:relative; }ol.timeline li:first-child{border-top:1px dashed #006699;} .delete_button { float:right; margin-right:10px; width:20px; height:20px } .cdelete_button { float:right; margin-right:10px; width:20px; height:20px } .feed_link { font-style:inherit; font-family:Georgia; font-size:13px;padding:10px; float:left; width:350px } .comment { color:#0000CC; text-decoration:underline } .delete_update { font-weight:bold; } .cdelete_update { font-weight:bold; } .post_box { height:55px;border-bottom:1px dashed #006699;background-color:#F3F3F3; width:499px;padding:.7em 0 .6em 0;line-height:1.1em; } #fullbox { margin-top:6px;margin-bottom:6px; display:none; } .comment_box { display:none;margin-left:90px; padding:10px; background-color:#d3e7f5; width:300px; height:50px; } .comment_load { margin-left:90px; padding:10px; background-color:#d3e7f5; width:300px; height:30px; font-size:12px; border-bottom:solid 1px #FFFFFF; } .text_area { width:290px; font-size:12px; height:30px; } #expand_box { margin-left:90px; margin-top:5px; margin-bottom:5px; } embed { width:200px; height:150px; } </style> </head> <body> <?php include '../../../settings.php'; ?> <div align="center"> <table cellpadding="0" cellspacing="0" width="500px"> <tr> <td> <div align="left"> <form method="post" name="form" action=""> <table cellpadding="0" cellspacing="0" width="500px"> <tr><td align="left"><div align="left"> <h3>What are you doing?</h3></div></td></tr> <tr> <td style="padding:4px; padding-left:10px;" class="update_box"> <textarea cols="30" rows="2" style="width:480px;font-size:14px; font-weight:bold" name="content" id="content" maxlength="145" ></textarea><br /> <input type="submit" value="Update" id="v" name="submit" class="comment_button"/> </td> </tr> </table> </form> </div> <div style="height:7px"></div> <div id="flash" align="left" ></div> <ol id="update" class="timeline"> </ol> <div id='old_updates'> <?php $small=mysql_query("select * from messages2 order by msg_id desc LIMIT 5"); while($r=mysql_fetch_array($small)) { $id=$r['msg_id']; $msg=$r['message']; ?> <div align="left" class="post_box"> <span style="padding:10px"><?php echo $msg.'....'.$id; ?> </span> </div> <ol> <?php //Here $id is main message msg_id value. $csql=mysql_query("select * from comments where msg_id_fk='$id' order by com_id "); $array = mysql_fetch_assoc($csql); $comment_count=mysql_num_rows($csql); if($comment_count>2) { $second_count=$comment_count-2; ?> <div class="comment_ui" id="view<?php echo $id; ?>"> <a href="#" class="view_comments" id="<?php echo $id; ?>">View all <?php echo $comment_count; ?> comments</a> </div> <?php } ?> <div id="view_comments<?php echo $id; ?>"></div> <div id="two_comments<?php echo $id; ?>"> <table width="50%"> <?php $small2=mysql_query("select * from comments where msg_id_fk='$id' order by com_id limit 2 "); while($rowsmall22=mysql_fetch_array($small2)) { $c_id=$rowsmall22['com_id']; $comments=$rowsmall22['comment']; ?> <div class="comment_actual_text"> <tr> <td style="BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; BORDER-LEFT: black 1px solid; BORDER-BOTTOM: black 1px solid" valign="top"> <table style="WIDTH: 100%; BORDER-COLLAPSE: collapse" align="left"> <tr> <td width="5%" style="VERTICAL-ALIGN: middle; TEXT-ALIGN: center"><img style="WIDTH: 30px; HEIGHT: 30px" alt="srinivas" src="http://www.gravatar.com/avatar.php?gravatar_id=7a9e87053519e0e7a21bb69d1deb6dfe" border="1" /></td> <td style="VERTICAL-ALIGN: top; TEXT-ALIGN: left"> <strong>Jarratt</strong> <?php echo $comments; ?> <br /><span style="COLOR: #a9a9a9">10 min ago - ID = <?php echo $c_id.'...'.$id;?> </span></td> </tr> </table><br /> </td> </tr> </div> <?php } ?> </table> </div> </ol> <?php } ?> </div> </td> </tr> </table> </div> </body> </html> |